How to insert data in Table of SQLite3 Database using Python

Inserting Data in Table in SQLite3 Database in Python

Inserting Data in database

Data to be inserted in the table is in form of  "Tuple".

Inserting data in database means we are inserting a new row with fixed no of columns ( columns created at time of table creation).

In brief, Tuple is a collection of heterogeneous data, written inside ()  (round brackets).


Query to insert data in database


"insert into Employee_Data(Column_name1, Column_name2)values(data, data)"
                            or
"INSERT INTO Employee_Data(Column_name1, Column_name2)values(data, data)"


Example on how to insert data directly in DATABASE (predefined data)


# program to insert data

import sqlite3 as sql

conn = sql.connect(
"Employee_Details.db") # creating connection with database(created in current directory)
curs = conn.cursor() # creating cursor to database

curs.execute("create table Employee_Data(Id number primary key, Name text, Salary number)")
curs.execute(
"insert into Employee_Data(Id, Name, Salary) values(55, 'Techno Xpresss', 20682.00)")
print("Data Inserted successfully")

conn.close()

 #Output

Data Inserted successfully


Lets have a look in BD_Browser


Oopsssss, no data is inserted, its because after inserting data, commit() API needs to call.


# program

import sqlite3 as sql

conn = sql.connect(
"Employee_Details.db") # creating connection with database(created in current directory)
curs = conn.cursor() # creating cursor to database

curs.execute("create table Employee_Data(Id number primary key, Name text, Salary number)")
curs.execute(
"insert into Employee_Data(Id, Name, Salary) values(55, 'Techno Xpresss', 20682.00)")
print("Data Inserted successfully")

conn.commit()
conn.close()

 #Output

Data Inserted successfully


Lets have a look in BD_Browser now once again after calling commit() API




Example on how to insert run time data directly in DATABASE


# program

import sqlite3 as sql

def get_employee_data():
Id =
int(input("Enter Employee ID : "))
Name =
input("Enter Employee Name : ")
Salary =
float(input("Enter Employee Salary : "))

return (Id, Name, Salary)


data = get_employee_data()

conn = sql.connect(
"Employee_Details.db") # creating connection with database(created in current directory)
curs = conn.cursor() # creating cursor to database

curs.execute("create table Employee_Data(Id number primary key, Name text, Salary float)")
curs.execute(
"insert into Employee_Data(Id, Name, Salary) values(?, ?, ?)", data)
print("Data Inserted successfully")

conn.commit()
conn.close()

 #Output

Enter Employee ID : 101
Enter Employee Name : Er M S Dandyan
Enter Employee Salary :
28602.08
Data Inserted successfully


Lets have a look in BD_Browser



Always remember to close the connection before closing or quitting your software.





Comments

My photo
Techno Xpresss
Bangalore, Karnataka, India