【问题标题】:Inserting an array into mysql with Python使用 Python 将数组插入 mysql
【发布时间】:2015-12-29 22:52:51
【问题描述】:

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

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

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

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

我在将数组变量正确传递到 mysql 时遇到问题。任何帮助表示赞赏。

【问题讨论】:

  • 这是一个类似问题的解决方案,希望对stackoverflow.com/questions/21612933/…有帮助
  • 最好也检查一下服务器的最大大小。你可以用SHOW VARIABLES LIKE 'max_allowed_packet'来做到这一点。

标签: python mysql arrays insert


【解决方案1】:

是的,你可以用 executemany 做到这一点:

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

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

【讨论】:

  • 不客气,看看笔记,我编辑了我的答案。
  • 我昨天打算更新:cursor.executemany('''INSERT IGNORE INTO %s (col1, col2, col3) VALUES (%%s, %%s, %%s)''' % 表名,(数组))
【解决方案2】:

这对我有用,试试吧。

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.")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 2016-03-13
    • 2018-03-02
    • 2011-05-14
    • 2013-11-17
    相关资源
    最近更新 更多