0 votes
in Python by
How to Insert Data in Python?

1 Answer

0 votes
by

Data stored in Python variables can be inserted into database tables.

Data is passed to SQL statements through parameter substitution.

Single rows are inserted using execute and multiple rows using executeMany method of created cursor object.

Inserting a Sample Data
Example 1
import sqlite3
# establishing the connection
con = sqlite3.connect('D:\\TEST.db')
# preparing a cursor object
cursor = con.cursor()
# preparing sql statement
rec = (456789, 'Frodo', 45, 'M', 100000.00)
sql = '''
      INSERT INTO EMPLOYEE VALUES ( ?, ?, ?, ?, ?)
# executing sql statement using try ... except blocks
try:
    cursor.execute(sql, reiii)
    con.commit()
except Exception as e:
    print("Error Message :", str(e))
    con.rollback()
# closing the database connection
con.close()
A single record is inserted into table EMPLOYEE.

Related questions

0 votes
asked Sep 25, 2021 in Python by john ganales
0 votes
asked Sep 5, 2021 in Python by SakshiSharma
...