python program to insert the value in table and show them using SQLite

In this session, we are just going to implement the logic for the insertion of data into the tale and fetch them to display. Let’s learn how to insert data into SQLite table in Python using sqlite3.

How to insert the data into the table in Python using sqlite3

before insertion 1st we have to create the table which I have already discussed in the previous session (Introduction to SQLite 3 with example in Python) but here we directly going to use them.

program for table creation with name of STUDENTS:




#import the sqlite package to use all in built function of sqlite.
 import sqlite3
#established the coonection
connec=sqlite3.connect('student.db')
print("Database has been created  successfully");
#now create a table with name of students
connec.execute('''CREATE TABLE STUDENTS
         (ROLLNO            NOT NULL,
         NAME1      char(23)    NOT NULL,

         ADDRESS1   char(30)
         );''')
print("STUDENTS table has been created successfully");
# closed the coonection.
connec.close()

Now insert the value in the table STUDENTS:

#import the sqlite package to use all in built function of sqlite.
 import sqlite3
 #established the coonection connec=sqlite3.connect('student.db') 
print("Database has been created successfully............");
 #insert the 3 students records 
connec.execute("INSERT INTO STUDENTS VALUES(829, 'raj', 32, 'patna')"); 
connec.execute("INSERT INTO STUDENTS VALUES(830, 'prakash', 25, 'odisha' )");
 connec.execute("INSERT INTO STUDENTS VALUES(831, 'raju', 16, 'kolkata' )");
 connec.commit()
 # closed the coonection. 
connec.close()

Now display the value of the table:

#import the sqlite package to use all in built function of sqlite.
import sqlite3
#established the coonection

connec= sqlite3.connect('students.db')
print("Database has been created  successfully....");
x=connec.execute("SELECT ROLLNO, name1, address1 from STUDENTS")
for row in x:
   print("ROLL =",row[0])
   print("NAME =",row[1])
   print("ADDRESS =",row[2],"\n")
# closed the coonection.
connec.close()

Output:

Database has been created  successfully.........
ROLLNO =  829
NAME1 =  raj
ADDRESS1 =  patna 

ROLLNO =  830
NAME1 =  prakash
ADDRESS1 =  odisha 

ROLLNO =  831
NAME1 =  raju
ADDRESS1 =  kolkata

Also learn:


Leave a Reply

Your email address will not be published. Required fields are marked *