python mysql insert multiple rows

Solutions on MaxInterview for python mysql insert multiple rows by the best coders in the world

showing results for - "python mysql insert multiple rows"
Shaun
03 Apr 2018
1import mysql.connector
2from mysql.connector import Error
3
4try:
5    connection = mysql.connector.connect(host='localhost',
6                                         database='Electronics',
7                                         user='pynative',
8                                         password='pynative@#29')
9
10    mySql_insert_query = """INSERT INTO Laptop (Id, Name, Price, Purchase_date) 
11                           VALUES (%s, %s, %s, %s) """
12
13    records_to_insert = [(4, 'HP Pavilion Power', 1999, '2019-01-11'),
14                         (5, 'MSI WS75 9TL-496', 5799, '2019-02-27'),
15                         (6, 'Microsoft Surface', 2330, '2019-07-23')]
16
17    cursor = connection.cursor()
18    cursor.executemany(mySql_insert_query, records_to_insert)
19    connection.commit()
20    print(cursor.rowcount, "Record inserted successfully into Laptop table")
21
22except mysql.connector.Error as error:
23    print("Failed to insert record into MySQL table {}".format(error))
24
25finally:
26    if (connection.is_connected()):
27        cursor.close()
28        connection.close()
29        print("MySQL connection is closed")
30
similar questions
queries leading to this page
python mysql insert multiple rows