Inserting variables to database table using Python
Last Updated :
02 Jul, 2021
In this article, we will see how one can insert the user data using variables.
Here, we are using the sqlite module to work on a database but before that, we need to import that package.
import sqlite3
To see the operation on a database level just download the SQLite browser database.
Note: For the demonstration, we have used certain values but you can take input instead of those sample values.
Steps to create and Insert variables in database
Code #1: Create the database
Python3
conn = sqlite3.connect('pythonDB.db')
c = conn.cursor()
Explanation:
We have initialised the database pythonDB.py. This instruction will create the database if the database doesn't exist. If the database having the same name as defined exist than it will move further. In the second statement, we use a method of sqlite3 named cursor(), this help you to initiate the database as active.
Cursors are created by the connection cursor() method, they are bound to the connection for the entire lifetime and all the commands are executed in the context of the database session wrapped by the connection.
Code #2: Create table
Python3
def create_table():
c.execute('CREATE TABLE IF NOT EXISTS RecordONE (Number REAL, Name TEXT)')
Explanation:
We have created a function create_table. This will help you to create table if not exist, as written in the query for SQLite database. As we have initiated the table name by RecordONE. After that we pass as many parameters as we want, we just need to give an attribute name along with its type, here, we use REAL and Text.
Code #3: Inserting into table
Python3
def data_entry():
number = 1234
name = "GeeksforGeeks"
c.execute("INSERT INTO RecordONE (Number, Name) VALUES(?, ?)",
(number, name))
conn.commit()
Explanation:
Another function called data_entry. We are trying to add the values into the database with the help of user input or by variables. We use the execute() method to execute the query. Then use the commit() method to save the changes you have done above.
Code #4: Method calling and Close the connection.
Python3
create_table()
data_entry()
c.close()
conn.close()
Explanation:
We normally use the method call, also remember to close the connection and database for the next use if we want to write error-free code because without closing we can't open the connection again.
Let's see the complete example now.
Example:
Python3
import sqlite3
conn = sqlite3.connect('pythonDB.db')
c = conn.cursor()
def create_table():
c.execute('CREATE TABLE IF NOT EXISTS RecordONE (Number REAL, Name TEXT)')
def data_entry():
number = 1234
name = "GeeksforGeeks"
c.execute("INSERT INTO RecordONE (Number, Name) VALUES(?, ?)", (number, name))
conn.commit()
create_table()
data_entry()
c.close()
conn.close()
Output:
Inserting one more value using data_entry() method.
Python3
def data_entry():
number = 4321
name = "Author"
c.execute("INSERT INTO RecordONE (Number, Name) VALUES(?, ?)", (number, name))
conn.commit()
Output:
Similar Reads
How to import CSV file in SQLite database using Python ? In this article, we'll learn how to import data from a CSV file and store it in a table in the SQLite database using Python. You can download the CSV file from here which contains sample data on the name and age of a few students. Contents of the CSV file Approach: Importing necessary modulesRead da
2 min read
Bulk Insert to Pandas DataFrame Using SQLAlchemy - Python Let's start with SQLAlchemy, a Python library that allows communication with databases(MySQL, PostgreSQL etc.) and Python. This library is used as an Object Relational Mapper tool that translates Python classes to tables in relational databases and automatically converts function calls to SQL statem
3 min read
How to Import a CSV file into a SQLite database Table using Python? In this article, we are going to discuss how to import a CSV file content into an SQLite database table using Python. Approach:At first, we import csv module (to work with csv file) and sqlite3 module (to populate the database table).Then we connect to our geeks database using the sqlite3.connect()
3 min read
Get the id after INSERT into MySQL database using Python Prerequisites: MySQL, mysql-connector for python The task here is to draft a Python program that works with SQL support to connect data. Whenever insertion into the database takes place, the ID of the row inserted will be printed. To connect python with the database we are using MySQL connector. The
2 min read
Python Database Tutorial Python being a high-level language provides support for various databases. We can connect and run queries for a particular database using Python and without writing raw queries in the terminal or shell of that particular database, we just need to have that database installed in our system.A database
4 min read
PostgreSQL - Connecting to the Database using Python PostgreSQL in Python offers a robust solution for developers looking to interact with databases seamlessly. With the psycopg2 tutorial, we can easily connect Python to PostgreSQL, enabling us to perform various database operations efficiently. In this article, we will walk you through the essential
4 min read