使用 Python 将数组插入 mysql

Inserting an array into mysql with Python

我正在构建这个包含 40k 个条目的数组。

array = [(value1, value2, value3),(value1, value2, value3),(value1, value2, value3) .... ]

是否可以将其插入到 mysql 中的 python 中,例如:

cursor.execute('''INSERT IGNORE into %s VALUES *array here*''' % (table_name, array))

我无法将数组变量正确传递到 mysql。任何帮助表示赞赏。

是的,您可以使用 executemany 来完成:

cursor.executemany('INSERT IGNORE into %s VALUES(%s, %s, %s)'%table_name, sql_data)

注意:您不应该使用%向数据库传递值,而是需要在execute/executemany的第二个参数中传递它们。我使用 % 作为 table 名称,因为第一个参数是准备好的查询字符串。

这是我用的试试。

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="",
  database="test"
)
mycursor = mydb.cursor()
print("Insert Process... Please Wait...")
for r in range(1,tdrows+1):
    a = []
    for c in range(1,tdcols+1):
        a.append(driver.find_element_by_xpath("//*[@id='DataTables_Table_0']/tbody/tr["+str(r)+"]/td["+str(c)+"]").text)
    sql = "INSERT IGNORE into test_table(id,fname,lname) VALUES (%s, %s, %s)"
    val = (a)
    mycursor.execute(sql,val)
    mydb.commit()
print(mycursor.rowcount, "Record Inserted.")