举例python对mysql的增删改查
时间: 2024-02-13 14:51:51 浏览: 74
可以使用Python标准库中的mysql.connector模块或第三方库pymysql来实现数据库的增删改查操作。
1.连接MySQL数据库
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="database_name"
)
2.查询数据
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
3.插入数据
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
4.更新数据
mycursor = mydb.cursor()
sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Highway 21'"
mycursor.execute(sql)
mydb.commit()
5.删除数据
mycursor = mydb.cursor()
sql = "DELETE FROM customers WHERE address = 'Canyon 123'"
mycursor.execute(sql)
mydb.commit()
阅读全文