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', host='hostname', database='databasename') # 获取游标对象 cursor = cnx.cursor() # 数据列表 data = [ ('John', 'Smith', 'email@example.com'), ('Jane', 'Doe', 'firstname.lastname@example.org'), ('Bob', 'Johnson', 'email@example.com') ] # INSERT 语句 insert_stmt = ("INSERT INTO customers " "(first_name, last_name, email) " "VALUES (%s, %s, %s)") # 循环写入数据 for row in data: # 执行 INSERT 语句 cursor.execute(insert_stmt, row) # 提交事务 cnx.commit() # 关闭游标和连接 cursor.close() cnx.close()
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
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.
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.