python访问sqlserver

来源:互联网 发布:unity3d上海 编辑:程序博客网 时间:2024/05/17 20:09

linux平台如果用python访问sqlserver

安装pymssql需要的包:

freetds(http://www.filewatcher.com/m/freetds-0.82.tar.gz.1596755-0.html)

setuptools(https://pypi.python.org/pypi/setuptools)

pymssql(https://pypi.python.org/pypi/pymssql/)



2. 安装setuptools

#tar zxvf setuptools-3.5.1.tar.gz

#cd setuptools-3.5.1

# python setup.py install


3. 安装pymssql

#tar zxvf pymssql-2.1.0.tar.gz

#cd pymssql-2.1.0

#python setup.py install

注:如果不安装freetds,会报如下错误:

error: command 'gcc' failed with exit status 1

wget ftp://ftp.openbsd.dk/.disk4/exherbo/freetds-0.82.tar.gztar zxvf freetds-0.82.tar.gzcd freetds-0.82./configure --prefix=/usr/local/freetds --with-tdsver=8.0 --enable-msdblib --enable-dbmfix --with-gnu-ld --enable-shared --enable-staticmake && make installecho "/usr/local/freetds/lib" >> /etc/ld.so.conf.d/freetds.confldconfig -v[root@test ~]# rpm -qa|grep setuptoolspython-setuptools-0.6.10-3.el6.noarch如果有结果就证明安装了否则需要安装setuptools-3.5.1.tar.gz进入页面进行下载pymssqlhttps://pypi.python.org/pypi/pymssql/2.1.3#downloadstar zxvf pymssql-2.1.3.tar.gz cd pymssql-2.1.3python setup.py install



模块安装完后就可以进入Python操作数据了

[root@test ~]# pythonPython 2.6.6 (r266:84292, Nov 22 2013, 12:16:22) [GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> import pymssql>>> conn = pymssql.connect(host ="xxxx:1433",database ="master",user="xxxx",password="xxxx")>>> cur = conn.cursor()>>> cur.execute("select getdate()")          >>> row = cur.fetchone()>>> print row(datetime.datetime(2016, 11, 18, 11, 5, 15, 630000),)>>> 


#举个例子

#-*-coding:gb2312-*-
import pymssql
#数据库连接
conn = pymssql.connect(host =".",database ="master",user="sa",password="1")
#定义游标
cur = conn.cursor()
#执行指定的sql
cur.execute("select * from dbo.bookshop")
#游标读取第一行
row = cur.fetchone()
for i in range(2):
   if i ==2:
       print row[0]," ".ljust(10-len(row[0])," "),row[1]," ".ljust(20-len(row[1])," "),row[2]
   row = cur.fetchone()
 
#关闭数据库连接
conn.close()

0 0
原创粉丝点击