1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
| # coding:utf-8
import pymssql
import sys
class MSSQL:
def __init__(self, host, port, user, pwd, db):
reload(sys)
sys.setdefaultencoding('utf8')
if not db:
raise(NameError, u"没有设置数据库信息")
self.conn = pymssql.connect(host=host, port=port, user=user, password=pwd, database=db, charset="utf8")
self.cur = self.conn.cursor()
if not self.cur:
raise(NameError, u"连接数据库失败")
# 执行查询等有返回的sql
def ExecQuery(self,sql):
cur = self.cur
cur.execute(sql)
resList = cur.fetchall()
return resList
# 执行删除等无返回的sql
def ExecNonQuery(self,sql):
cur = self.cur
cur.execute(sql)
self.conn.commit()
def colseDB(self):
self.conn.close()
if __name__ == '__main__':
ms = MSSQL(host="172.16.0.137", port='3433', user="test1", pwd="test1234", db="db1533")
insertSql = "INSERT INTO Stu_Info ([NO], [Name], [Sex]) VALUES (1001,'张三','男');"
selectSql = "select NO,Name from Stu_Info where No=1001;"
ms.ExecNonQuery(insertSql)
resList = ms.ExecQuery(selectSql)
for (id, name) in resList:
print str(name)
|