用与连接sql server数据库的python接口
import pymssql
1.配置信息
conf={
"host": "118.190.41.846:9099",
"user": "sa",
"password": "123",
"database": "water"}
如果是连接本地的数据库,host可以写为本机的数据库名例‘DESKTOP-K06BHO8’
2.连接数据库
conn=pymssql.connect(**conf)
cur=conn.cursor() #默认返回元组,使用as_dict='True'设置为返回字典形式的列表
#用with功能,避免忘记关闭连接与游标
# with pymssql.connect(**config["test2"]) as conn:
# with conn.cursor(as_dict=True) as cursor:
# cursor.execute('SELECT top 10 * FROM tbluserinfo WHERE userid=%s', 'John Doe')
# #通过迭代方式获取查询结果
# for row in cursor:
# print("ID=%d, Name=%s" % (row['id'], row['name']))
# conn.commit()
3.执行sql语句
sql='select * from readdata'
cur.execute(sql)
execute('insert into test3(username,address,type) values(%s,%s,%d)',('wingwed','3 street 4 block',3))
该方法有两个参数,可在sql语句中使用入参,字符型用%s,数字型用%d,
第二个参数必须是元组或dict类型,列表类型会报错。
也可一次写入多条记录
executemany("INSERT INTO persons VALUES (%d, %s, %s)",
[(1, 'John Smith', 'John Doe'),
(2, 'Jane Doe', 'Joe Dog'),
(3, 'Mike T.', 'Sarah H.')])
4.获取执行结果
data=cur.fetchall()#获取所有结果,返回每条记录元组组成的列表
#data=cur.fetchone() 获取一条结果,返回单个元组,当查询结果记录数为0时,不会报错,会返回None.
#通过迭代方式获取查询结果
# for row in cur:
# print("ID=%d, Name=%s" % (row['id'], row['name']))
#5.调用存储过程
# 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']))