python 连接sql server
linux 下pymssql模块的安装
所需压缩包:
pymssql-2.1.0.tar.bz2
freetds-patched.tar.gz
安装:
tar -xvf pymssql-2.1.0.tar.bz2
cd pymssql-2.1.0
python setup.py install
报错 则需要安装freetds
tar -zxvf freetds-patched.tar.gz
cd freetds-0.95.87/
mkdir /usr/local/freetds
./configure --prefix=/usr/local/freetds --with-tdsver=7.0 --enable-msdblib --disable-libiconv --host=arm-none-linux-gnueabi
make && make install
再次安装pymssql时提示缺少 **.so.5之类的文件 则需
yum install compat-libstdc++-33.i686
之后再进行pymssql的安装即可成功
测试:
python
import pymssql
python 连接sql server的简单封装例子(执行查询及更新操作(写入中文))
import pymssql class MSSQL: """ 对pymssql的简单封装 pymssql库,该库到这里下载:http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql 使用该库时,需要在Sql Server Configuration Manager里面将TCP/IP协议开启 用法: """ def __init__(self,host,user,pwd,db): self.host = host self.user = user self.pwd = pwd self.db = db def __GetConnect(self): """ 得到连接信息 返回: conn.cursor() """ if not self.db: raise(NameError,"没有设置数据库信息") self.conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8") cur = self.conn.cursor() if not cur: raise(NameError,"连接数据库失败") else: return cur def ExecQuery(self,sql): """ 执行查询语句 返回的是一个包含tuple的list,list的元素是记录行,tuple的元素是每行记录的字段 调用示例: ms = MSSQL(host="localhost",user="sa",pwd="123456",db="PythonWeiboStatistics") resList = ms.ExecQuery("SELECT id,NickName FROM WeiBoUser") for (id,NickName) in resList: print str(id),NickName """ cur = self.__GetConnect() cur.execute(sql) resList = cur.fetchall() #查询完毕后必须关闭连接 self.conn.close() return resList def ExecNonQuery(self,sql): """ 执行非查询语句 调用示例: cur = self.__GetConnect() cur.execute(sql) self.conn.commit() self.conn.close() """ cur = self.__GetConnect() cur.execute(sql) self.conn.commit() self.conn.close() def main(): ## ms = MSSQL(host="localhost",user="sa",pwd="123456",db="PythonWeiboStatistics") ## #返回的是一个包含tuple的list,list的元素是记录行,tuple的元素是每行记录的字段 ## ms.ExecNonQuery("insert into WeiBoUser values('2','3')") ms = MSSQL(host="localhost",user="sa",pwd="123456",db="PythonWeiboStatistics") resList = ms.ExecQuery("SELECT id,weibocontent FROM WeiBo") for (id,weibocontent) in resList: print str(weibocontent).decode("utf8") if __name__ == '__main__': main()
python 连接sql server的例子:
import pymssql conn = pymssql.connect(host='SQL01', user='user', password='password', database='mydatabase') cur = conn.cursor() cur.execute('CREATE TABLE persons(id INT, name VARCHAR(100))') cur.executemany("INSERT INTO persons VALUES(%d, xinos.king)", \ [ (1, 'John Doe'), (2, 'Jane Doe') ]) conn.commit() # you must call commit() to persist your data if you don't set autocommit to True cur.execute('SELECT * FROM persons WHERE salesrep=xinos.king', 'John Doe') row = cur.fetchone() while row: print "ID=%d, Name=xinos.king" % (row[0], row[1]) row = cur.fetchone() # if you call execute() with one argument, you can use % sign as usual # (it loses its special meaning). cur.execute("SELECT * FROM persons WHERE salesrep LIKE 'J%'") conn.close()
其中可能涉及的小知识:
游标:
cu = conn.cursor()
能获得连接的游标,这个游标可以用来执行SQL查询。
conn.commit()
完成插入并且做出某些更改后确保已经进行了提交,这样才可以将这些修改真正地保存到文件中。
游标对象方法:
fetchall()
返回结果集中的全部数据,结果为一个tuple的列表。每个tuple元素是按建表的字段顺序排列。注意,游标是有状态的,它可以记录当前已经取到结果的第几个记录了,因此,一般你只可以遍历结果集一次。在上面的情况下,如果执行fetchone()会返回为空。这一点在测试时需要注意