import pymssql标签:demo,execute,python,改查,sqlserver,cursor,sql,print,db From: https://www.cnblogs.com/dawei163/p/16902622.html
# 打开数据库连接
db = pymssql.connect(server='localhost', user='sa', password='888888',database='customerdb')
# 创建游标对象,并设置返回数据的类型为字典
cursor = db.cursor(as_dict=True)
# 设置立即操作
db.autocommit(True)
# 插入
sql = "insert into demo (name,dec) values (%s,%s);"
#单条记录
cursor.execute(sql,('cx','jamesdec'))
for m in range(2,10):
cursor.execute(sql,('cx'+str(m),'jamesdec'+str(m)))
print(sql)
cursor.executemany(sql,[('cx','jamesdec'),('cx','jamesdec')])
#删除
sql="delete demo where id=%s"
cursor.execute(sql,(442742))
#sql like查询
sql="update demo set name='kkkkkkkkk' where name LIKE '%s'" % ('%%%s%%' % 'kx')
cursor.execute(sql)
print('******************************************************')
print(sql)
print('******************************************************')
db.commit()
#查询
"""
查询一种写法
sql: str="select * from demo where id=%s"%'442632'
cursor.execute(sql)
data=cursor.fetchall()
print(sql)
print(data)
"""
# 查询另外一种写法
sql: str="select * from demo where name=%s"
cursor.execute(sql,('kxkx'))
data=cursor.fetchall()
print(sql)
print(data)
# 关闭游标与数据库连接
cursor.close()
db.close()