我想在表中插入一个新条目,然后将每个列的值作为数组的索引。因此,当我尝试添加它时,我会这样做:
query = """INSERT INTO table VALUES(?, ?, ?)"""
cursor.execute(query, (data,))
connection.commit()
对于更大的数据列表,我也必须做同样的事情,因此,比调用data [0],data [1],data [2]更好的方法会受到赞赏
答案 0 :(得分:0)
我不确定当您说我将每个列的值作为数组的索引时我是否理解正确,但是假设您的表格人员具有名字,姓氏,年龄列,并且您的数据是像这样
data = [[“ Hans”,“ Muster”,23],[“ Jane”,“ Doe”,46],[“ John”,“ Doe”,26]]
实现插入的两种可能的简短方法是。
选项1-您可以一次迭代并保存一条记录
# get connection and cursor object
query= "INSERT INTO PERSON (FIRSTNAME, LASTNAME, AGE) VALUES (%s, %s, %s)"
for rec in data:
record = tuple(rec)
cursor.execute(query, record)
#handle commit or rollback as necessary
选项2-您可以使用executemany一口气保存所有记录
# get connection and cursor object
query= "INSERT INTO PERSON (FIRSTNAME, LASTNAME, AGE) VALUES (%s, %s, %s)"
tupleRecords = [tuple(rec) for rec in data]
cursor.executemany(query, tupleRecords)
#handle commit or rollback as necessary
答案 1 :(得分:-1)
您可以执行以下操作来插入值列表。资源: https://www.w3schools.com/python/python_mysql_insert.asp
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
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, "was inserted.")