用python写一个mysql的增删改查程序
时间: 2023-03-14 20:33:18 浏览: 95
python操作mysql数据库实现增删查改
我可以给您一个参考:import mysql.connector# 建立数据库连接
conn = mysql.connector.connect(user='root', password='password', database='test', host='127.0.0.1')# 创建游标
cursor = conn.cursor()# 插入
sql = "INSERT INTO table_name (id, name) VALUES (%s, %s)"
val = (1, 'John')
cursor.execute(sql, val)
conn.commit()# 查询
sql = "SELECT * FROM table_name"
cursor.execute(sql)
results = cursor.fetchall()for row in results:
print(row)
# 更新
sql = "UPDATE table_name SET name=%s WHERE id=%s"
val = ('Peter', 1)
cursor.execute(sql, val)
conn.commit()# 删除
sql = "DELETE FROM table_name WHERE id=%s"
val = (1,)
cursor.execute(sql, val)
conn.commit()# 关闭数据库连接
cursor.close()
conn.close()
阅读全文