在Python中,可以使用MySQL Connector库来连接MySQL数据库,并使用SQL语句来更新多条记录。下面是使用Python更新多条MySQL记录的步骤:
pip install mysql-connector-python
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
mycursor = mydb.cursor()
data = [
('John', 'Highway 21', 1),
('Peter', 'Lowstreet 4', 2),
('Amy', 'Apple st 652', 3)
]
sql = "UPDATE customers SET name = %s, address = %s WHERE id = %s"
mycursor.executemany(sql, data)
mydb.commit()
print(mycursor.rowcount, "记录被更新")
完整的代码示例:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
mycursor = mydb.cursor()
data = [
('John', 'Highway 21', 1),
('Peter', 'Lowstreet 4', 2),
('Amy', 'Apple st 652', 3)
]
sql = "UPDATE customers SET name = %s, address = %s WHERE id = %s"
mycursor.executemany(sql, data)
mydb.commit()
print(mycursor.rowcount, "记录被更新")
这样,你就可以使用Python一次性更新多条MySQL记录了。在上述代码中,我们使用了executemany()
方法来执行更新操作,并使用commit()
方法提交更改。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云