python访问sqlserver

    xiaoxiao2021-11-29  32

    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()

    转载请注明原文地址: https://ju.6miu.com/read-678659.html

    最新回复(0)