Create Table and Execute Query in Sqlite3 Python by R4R Team

- execute() is a sqlite3 function that are used to execute the different queries on the database.

Syntax-

conn.execute(query)

Create a table :

program-

import sqlite3

#connect yo database
conn=sqlite3.connect('r4rDatabase.db')
print("Database is successfully created")

#create a table
conn.execute("create table r4rtable (Name char[20],age int,mobileno int)")
print("Table of name 'r4rtable' is created")
conn.close()


output-

Database is successfully created
Table of name 'r4rtable' is created

-In this program, we open a database of name 'r4rdatabase', in this database we create a table of name 'r4rtable'.

Insert into Table :

program-

import sqlite3

#connect yo database
conn=sqlite3.connect('r4rDatabase.db')
print("Database is successfully connected")

#insert data into r4rtable table
query='''insert into r4rtable (name,age,mobileno) values('Amit',10,12345)'''
conn.execute(query)

query='''insert into r4rtable (name,age,mobileno) values('Ajay',12,15321)'''
conn.execute(query)

query='''insert into r4rtable (name,age,mobileno) values('Abhay',20,54321)'''
conn.execute(query)

query='''insert into r4rtable (name,age,mobileno) values('Sita',10,12458)'''
conn.execute(query)

query='''insert into r4rtable (name,age,mobileno) values('Geetu',12,12345789)'''
conn.execute(query)
print("Insert 5 data successfully")
conn.commit()

conn.close()


output-

Database is successfully connected
Insert 4 data successfully


Fatch the data from database :

import sqlite3

#connect to database
conn=sqlite3.connect('r4rDatabase.db')
print("Database is successfully connected")

data=conn.execute("select * from r4rtable")
for row in data:
print("nName : ",row[0])
print("Age : ",row[1])
print("Mobile no. :",row[2])

conn.close()


output-

Database is successfully connected

Name : Amit
Age : 10
Mobile no. : 12345

Name : Ajay
Age : 12
Mobile no. : 15321

Name : Abhay
Age : 20
Mobile no. : 54321

Name : Sita
Age : 10
Mobile no. : 12458

Name : Geetu
Age : 12
Mobile no. : 12345789




Leave a Comment: