Python连接mysql实现增删改查基本操作

使用模块pymysql

import pymysql
# connect(mysql数据库IP地址,用户名,密码,连接的数据库名)
db = pymysql.connect('10.25.34.68','root','root','mydb')
# cursor光标,创建一个用于写sql语句的对象
cursor=db.cursor()
# execute执行sql语句
cursor.execute("select * from dept")
# 查询操作用fetchall获取,将数据以[(第一条记录),(第二条记录)...]形式返回
data=cursor.fetchall()
print(data)
# 增删改操作无返回结果,正常编写sql语句即可
# 支持事务
sql="insert into dept values (50,'demo','demo')"
try:
    cursor.execute(sql)
    db.commit()# 提交事务
    print('ok')
except:
    print('fail')
    db.rollback()# 事务失败回滚到try之前
# 最后关闭连接
db.close()

猜你喜欢

转载自blog.csdn.net/wxfghy/article/details/81029583