Open In App

How to Execute a SQLite Statement in Python?

In this article, we are going to see how to execute SQLite statements using Python. We are going to execute how to create a table in a database, insert records and display data present in the table.

In order to execute an SQLite script in python, we will use the execute() method with connect() object:



connection_object.execute(“sql statement”)

Approach:

To perform the execution, we have to follow the below steps:



import sqlite3
connection_object = sqlite3.connect('database_name.db')
connection_object.execute("sql statement");
connection_object.close();

Example 1: Python code to create a database and a table, below are the steps:




# importing sqlite3 module
import sqlite3
  
# create connection by using object to 
# connect with college_details database
connection = sqlite3.connect('college.db')
  
  
# sqlite execute query to create a table
connection.execute("""create table college(
        geek_id,
        geek_name,
        address
    );""")
  
print("Table created successfully")
  
# terminate the connection
connection.close()

Output:

Database created:

Example 2: Python code to insert and display data into the above-created table.




# importing sqlite3 module
import sqlite3
  
# create connection by using object 
# to connect with college_details 
# database
connection = sqlite3.connect('college.db')
  
# sqlite execute query to insert a table
connection.execute(
    '''insert into college values ( '7058', 'sravan kumar','hyd' )''')
connection.execute(
    '''insert into college values ( '7059', 'jyothika','tenali' )''')
connection.execute(
    '''insert into college values ( '7072', 'harsha verdhan','nandyal' )''')
connection.execute(
    '''insert into college values ( '7099', 'virinchi','Guntur' )''')
  
# sqlite execute query to display data
# in the college
a = connection.execute("select * from college")
  
# fetch all records
print(a.fetchall())
  
# terminate the connection
connection.close()

Output:


Article Tags :