The python connection to the database cannot write data

darydong 注册会员
2023-02-28 00:05

does2006 注册会员
2023-02-28 00:05

INSERT statements are executed separately for each piece of data, rather than executing the same INSERT statement multiple times in the loop.

Here is an example code that shows how to connect to a MySQL database using Python and write multiple pieces of data in a loop:

import mysql.connector

# 连接到数据库
cnx = mysql.connector.connect(user='username', password='password',

# 获取游标对象
cursor = cnx.cursor()

# 数据列表
data = [
    ('John', 'Smith', 'jsmith@example.com'),
    ('Jane', 'Doe', 'jdoe@example.com'),
    ('Bob', 'Johnson', 'bjohnson@example.com')

insert_stmt = ("INSERT INTO customers "
               "(first_name, last_name, email) "
               "VALUES (%s, %s, %s)")

# 循环写入数据
for row in data:
    # 执行 INSERT 语句
    cursor.execute(insert_stmt, row)

# 提交事务

# 关闭游标和连接

uses a data list to store multiple pieces of data to be written to the database. We then loop through the list of data, executing INSERT statements on each data separately. In this way, each data is written to the database without overwriting previous data

crocodileone 注册会员
2023-02-28 00:05

You did not provide your code, it is difficult to analyze.
To insert data in python, you can define a function and call it in batches. Each call inserts one piece of data without overwriting the previous data.

diamondsuper 注册会员
2023-02-28 00:05

Write based on Monster group and GPT:
If you use Python to connect to the MySQL database, only one piece of data is written to the database. The possible causes are as follows:

  • The transaction is not committed using the commit() method.
    By default, MySQL does not write data to disk immediately, but stores them in memory and does not write them to disk until a transaction is committed. Therefore, when inserting data into the database, you need to commit the transaction using the commit() method to ensure that the data is written to disk.

  • No executemany() method is used to insert multiple pieces of data.
    If you want to insert multiple pieces of data, you can use the executemany() method to insert multiple pieces of data at once instead of the execute() method to insert a single piece of data.

  • Each time the execute() method is executed, the previous data is overwritten.
    If the same SQL statement is used every time the execute() method is executed, the previous data written to the database is overwritten each time, and only the last data written is preserved.

About the Author

Question Info

Publish Time
2023-02-28 00:05
Update Time
2023-02-28 00:05

Related Question







Selenium Web驱动程序无法找到css选择器,即使它存在(python)


React setState不保存访问localStorage的组件列表