six7zero9
six7zero9

Reputation: 323

Inserting an array into mysql with Python

I am building this array with 40k entries.

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

Is it possible to insert this into mysql in python something like:

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

I am having trouble passing the array variable into mysql correctly. Any help appreciated.

Upvotes: 2

Views: 20526

Answers (2)

Thai Mozhi Kalvi
Thai Mozhi Kalvi

Reputation: 533

This is Use for me try it.

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

Upvotes: 0

ahmed
ahmed

Reputation: 5600

Yes you can do it with executemany:

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

Note: you shouldn't use % to pass values to the database, instead you need to pass them in the second parameter of execute/executemany. i used % for the table name because the first parameter is the prepared query string.

Upvotes: 7

Related Questions