python访问sqlserver

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.gz
tar zxvf freetds-0.82.tar.gz
cd freetds-0.82
./configure --prefix=/usr/local/freetds --with-tdsver=8.0 --enable-msdblib --enable-dbmfix --with-gnu-ld --enable-shared --enable-static
make && make install
echo "/usr/local/freetds/lib" >> /etc/ld.so.conf.d/freetds.conf
ldconfig -v
[root@test ~]# rpm -qa|grep setuptools
python-setuptools-0.6.10-3.el6.noarch
如果有结果就证明安装了
否则需要安装setuptools-3.5.1.tar.gz
进入页面进行下载pymssql
https://pypi.python.org/pypi/pymssql/2.1.3#downloads
tar zxvf pymssql-2.1.3.tar.gz 
cd pymssql-2.1.3
python setup.py install



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

[root@test ~]# python
Python 2.6.6 (r266:84292, Nov 22 2013, 12:16:22) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值