How to loop through adding data to the database

Using a loop statement to repeatedly add data to a database can be achieved. Below is an example code demonstrating how to use a Python loop to add data to a database one by one:

import sqlite3

# 建立数据库连接
conn = sqlite3.connect('your_database.db')
cursor = conn.cursor()

# 创建表格(如果不存在的话)
cursor.execute('''CREATE TABLE IF NOT EXISTS your_table
                  (id INTEGER PRIMARY KEY AUTOINCREMENT,
                   name TEXT,
                   age INTEGER)''')

# 定义要添加的数据列表
data_list = [('Alice', 25), ('Bob', 30), ('Charlie', 35)]

# 循环添加数据
for data in data_list:
    name, age = data
    cursor.execute("INSERT INTO your_table (name, age) VALUES (?, ?)", (name, age))

# 提交事务并关闭连接
conn.commit()
conn.close()

In this example, we demonstrate using an SQLite database. We first establish a connection to the database, then create a table called “your_table” if it does not exist. Next, we define a list of data called data_list, with each element containing a name and age. We then loop through the data list, adding each data to the database. Finally, we commit the transaction and close the database connection.

Please note that the above example uses an SQLite database. If you are using a different type of database, you will need to modify the connection and operation statements accordingly.

bannerAds