Executing SQLite3 Queries – Creating Tables
After connecting to the database and creating the cursor object let’s see how to execute the queries.
- To execute a query in the database, create an object and write the SQL command in it with being commented. Example:- sql_comm = ”SQL statement”
- And executing the command is very easy. Call the cursor method execute() and pass the name of the sql command as a parameter in it. Save a number of commands as the sql_comm and execute them. After you perform all your activities, save the changes in the file by committing those changes and then lose the connection.
Example: Creating SQLite3 tables using Python
In this example, we will create the SQLite3 tables using Python. The standard SQL command will be used for creating the tables.
Python
import sqlite3 # connecting to the database connection = sqlite3.connect( "gfg.db" ) # cursor crsr = connection.cursor() # SQL command to create a table in the database sql_command = """CREATE TABLE emp ( staff_number INTEGER PRIMARY KEY, fname VARCHAR(20), lname VARCHAR(30), gender CHAR(1), joining DATE);""" # execute the statement crsr.execute(sql_command) # close the connection connection.close() |
Output:
SQL using Python
In this article, integrating SQLite3 with Python is discussed. Here we will discuss all the CRUD operations on the SQLite3 database using Python. CRUD contains four major operations –
Note: This needs a basic understanding of SQL.
Here, we are going to connect SQLite with Python. Python has a native library for SQLite3 called sqlite3. Let us explain how it works.