python3连接sql sever2012并实现批量增删改查

项目需要,今天做了python连接SQL sever2012,并实现了批量增删改查操作。首先需要安装pymssql,这个可以使用pip install pymssql来进行安装,安装好后可以按照代码来操作。我的数据表只有id和name两个,这样简单易学

import pymssql
conn = pymssql.connect(host="127.0.0.1:1433", user="sa", password="123456", database="HZL09", charset="utf8")
#获取光标
cur = conn.cursor()
if not cur:
    raise (NameError,"数据库连接失败")
#conn.commit,可以从数据库中删除。否则只能打印的时候删除,增删改都需要
#插入数据
sql1 = "insert into test values(89,'爱因斯坦')"
cur.execute(sql1)
conn.commit()
#批量插入数据,注意要把"int"转化为"str"
for i in range(9,20):
    str_i = str(i)
    sql1 = "insert into test values(" + str_i + ",'郭')"
    cur.execute(sql1)
    conn.commit()
#删除
sql2 = "delete from test where id=2"
cur.execute(sql2)
conn.commit()
#改写
sql3 = "update test set id=2,name='牛顿' where id=1"
cur.execute(sql3)
conn.commit()
# 查找,结果按照id排序
sql4 = 'select * from test order by id'
cur.execute(sql4)
resList = cur.fetchall()#fetchall()是接收全部的返回结果行
conn.close()
print(resList)

你可能感兴趣的:(python学习足迹)