Python是一种高级编程语言,广泛用于Web开发、数据分析、人工智能等领域。MySQL是一种关系型数据库管理系统,用于存储和管理数据。Python可以通过各种库(如mysql-connector-python
、pymysql
等)与MySQL进行交互,实现数据的插入、查询、更新和删除。
INSERT INTO
语句插入单条记录。INSERT INTO
语句插入多条记录。以下是一个使用mysql-connector-python
库向MySQL插入数据的示例:
import mysql.connector
# 连接到MySQL数据库
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# 创建游标对象
mycursor = mydb.cursor()
# 插入单条数据
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
# 插入多条数据
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = [
('Peter', 'Lowstreet 4'),
('Amy', 'Apple st 652'),
('Hannah', 'Mountain 21'),
('Michael', 'Valley 345'),
('Sandy', 'Ocean blvd 2'),
('Betty', 'Green Grass 1'),
('Richard', 'Sky st 331'),
('Susan', 'One way 98'),
('Vicky', 'Yellow Garden 2'),
('Ben', 'Park Lane 38'),
('William', 'Central st 954'),
('Chuck', 'Main Road 989'),
('Viola', 'Sideway 1633')
]
mycursor.executemany(sql, val)
# 提交事务
mydb.commit()
print(mycursor.rowcount, "条记录已插入。")
# 关闭连接
mycursor.close()
mydb.close()
通过以上步骤和示例代码,你应该能够成功地将数据插入到MySQL数据库中。如果遇到具体问题,请根据错误信息进行排查和解决。
没有搜到相关的沙龙