Python和MySQL:插入数据

使用Python向MySQL数据库插入数据,我们需要编写一个SQL语句并执行它。

📘 示例

python
import mysql.connector

# 连接数据库
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="yourdatabase"
)

# 创建游标对象
cursor = mydb.cursor()

# 定义INSERT语句
sql = "INSERT INTO customers (name, email) VALUES (%s, %s)"
values = ("John Doe", "johndoe@example.com")

# 执行INSERT语句
cursor.execute(sql, values)

# 提交更改到数据库
mydb.commit()

# 打印受影响的行数
print(cursor.rowcount, "条记录已插入。")

# 关闭游标和数据库连接
cursor.close()
mydb.close()

在上面的代码中,我们首先导入mysql.connector模块以与MySQL数据库建立连接。
然后,我们创建一个游标对象来执行SQL语句。

接下来,我们使用INSERT INTO语法定义INSERT语句。
我们指定要插入数据的表名和列名。
在这个示例中,我们向"customers"表中插入一个姓名和一个电子邮件地址。

在定义INSERT语句之后,我们使用游标对象的execute()方法来执行它。
我们将SQL语句和要插入的值作为参数传递。

一旦INSERT语句执行完毕,我们需要使用数据库连接对象的commit()方法将更改提交到数据库。

最后,我们打印INSERT语句影响的行数,并关闭游标和数据库连接。

注意:请确保将"yourusername"、"yourpassword"和"yourdatabase"替换为您实际的MySQL凭据。