在使用python代码对数据库进行更新(Update)的时候,需要注意的地方有sql语句中where条件和set
的值要使用单引号,最后使用try except
对其进行异常处理,执行sql语句后使用conn.commit()
提交到数据库,代码如下:
import pymysql as mysql
# 连接database 给出host本地的地址 user和password 连接数据库的账号和密码
# 字符编码 数据库的名称
conn = mysql.connect(host="127.0.0.1", user="root",
password="root", charset="utf8", database="student")
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor() # 执行完毕返回的结果集默认以元组显示
# 定义要执行的SQL语句
sql = "update t_gread set sname='李户' where sno='1825123607'"
try:
cursor.execute(sql)
conn.commit()
except:
# 如果发生错误则回滚
conn.rollback()
print("更新失败")
# 关闭光标对象
cursor.close()
# 关闭数据库连接
conn.close()
在使用删除操作时,与更新同样,修改掉sql语句即可,不作过多解释,代码如下:
import pymysql as mysql
# 连接database 给出host本地的地址 user和password 连接数据库的账号和密码
# 字符编码 数据库的名称
conn = mysql.connect(host="127.0.0.1", user="root", password="root",
charset="utf8", database="student")
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor() # 执行完毕返回的结果集默认以元组显示
# 定义要执行的SQL语句
sql = "delete from t_gread where sname='张虎'"
try:
cursor.execute(sql)
conn.commit()
except:
# 如果发生错误则回滚
conn.rollback()
print("更新失败")
# 关闭光标对象
cursor.close()
# 关闭数据库连接
conn.close()