一个简单的 Python 数据库接口,构建在 FreeTDS 之上,为Microsoft SQL Server提供 Python DB-API (PEP-249)接口。
有关pymssql的详细信息可在网站上找到:
GitHub 上正在发生新的开发:
有一个谷歌小组供讨论:
pymssql wheels可从 PyPi 获得。要安装它,请运行:
pip install -U pip
pip install pymssql
import pymssql
server = "10.36.40.115" # 连接服务器地址
user = "sa" # 连接帐号
password = "xc@hn520" # 连接密码
database = "MSSQL_TEST"
conn = pymssql.connect(server, user, password, database) #获取连接
cursor = conn.cursor() # 获取游标
# 创建表
cursor.execute("""
IF OBJECT_ID('persons', 'U') IS NOT NULL
DROP TABLE persons
CREATE TABLE persons (
id INT NOT NULL,
name VARCHAR(100),
salesrep VARCHAR(100),
PRIMARY KEY(id)
)
""")
# 插入数据
cursor.execute("INSERT INTO persons VALUES (0, 'tt', 'test')")
# 插入多行数据
cursor.executemany(
"INSERT INTO persons VALUES (%d, %s, %s)",
[(1, 'John Smith', 'John Doe'),
(2, 'Jane Doe', 'Joe Dog'),
(3, 'Mike T.', 'Sarah H.')])
# 如果没有将自动提交设置为true,必须调用 commit() 提交数据
conn.commit()
# 查询数据
cursor.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')
# 遍历数据(存放到元组中) 方式1
row = cursor.fetchone()
while row:
print("ID=%d, Name=%s" % (row[0], row[1]))
row = cursor.fetchone()
# 遍历数据(存放到元组中) 方式2
for row in cursor:
print('row = %r' % (row,))
# 关闭游标
cursor.close()
# 关闭连接
conn.close()
注:在任何时候,在一个连接下,一次正在执行的数据库操作只会出现一个cursor对象
with pymssql.connect(server, user, password, database) as conn:
with conn.cursor(as_dict=True) as cursor: # 数据存放到字典中
cursor.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')
for row in cursor:
print("ID=%d, Name=%s" % (row['id'], row['name']))
with pymssql.connect(server, user, password, database) as conn:
with conn.cursor(as_dict=True) as cursor: # 数据存放到字典中
cursor.execute("""
CREATE PROCEDURE FindPerson
@name VARCHAR(100)
AS BEGIN
SELECT * FROM persons WHERE name = @name
END
""")
cursor.callproc('FindPerson', ('Jane Doe',))
for row in cursor:
print("ID=%d, Name=%s" % (row['id'], row['name']))