The Wayback Machine - https://web.archive.org/web/20241001172014/https://www.geeksforgeeks.org/python-sqlite-creating-a-new-database/
Open In App

Python SQLite – Creating a New Database

Last Updated : 20 May, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will discuss how to create a Database in SQLite using Python.

Creating a Database

You do not need any special permissions to create a database. The sqlite3 command used to create the database has the following basic syntax

Syntax: $ sqlite3 <database_name_with_db_extension>

The database name must always be unique in the RDBMS.

Example:

Image

When we create a sqlite database.

Similarly, we can create this database in python using the SQlite3 module.

Python3




import sqlite3
  
# filename to form database
file = "Sqlite3.db"
  
try:
  conn = sqlite3.connect(file)
  print("Database Sqlite3.db formed.")
except:
  print("Database Sqlite3.db not formed.")


Output:

Database Sqlite3.db formed.

Connect Database:

Creating a brand-new SQLite database is as easy as growing a connection to the usage of the sqlite3 module inside the Python preferred library. To establish a connection, all you have to do is to pass the file path to the connect(…) method in the sqlite3 module. If the database represented by the file does not exist, it will be created under this path.

import sqlite3
connection = sqlite3.connect(<path_to_file_db.sqlite3>)

Let’s see some description about connect() method,

Syntax: sqlite3.connect(database [, timeout , other optional arguments])

The use of this API opens a connection to the SQLite database file. Use “:memory:” to set up a connection to a database placed in RAM in place of the hard disk. A Connection object will be returned, when a database opened correctly.

The database can be accessed through multiple connections, and one of the processes is modifying the database. The SQLite database will hang until the transaction is committed. The timeout parameter specifies how long the connection should wait to unlock before throwing an exception. Timeout parameter 5.0 (five seconds). If the specified database name does not exist, this call will create the database.

If we want to create database data in a location other than the current directory, we can also use the desired path to specify the file name.

Implementation:

1. Creating a Connection between sqlite3 database and Python Program

sqliteConnection = sqlite3.connect('SQLite_Retrieving_data.db')

2.  If sqlite3 makes a connection with the python program then it will print “Connected to SQLite”, Otherwise it will show errors

print("Connected to SQLite")

3. If the connection is open, we need to close it. Closing code is present inside the final Block. We will use close() method for closing the connection object. After closing the connection object, we will print “the SQLite connection is closed”

if sqliteConnection:
    sqliteConnection.close()
    print("the sqlite connection is closed")

Python3




# Importing Sqlite3 Module
import sqlite3
  
try:
    # Making a connection between sqlite3 database and Python Program
    sqliteConnection = sqlite3.connect('SQLite_Retrieving_data.db')
    # If sqlite3 makes a connection with python program then it will print "Connected to SQLite"
    # Otherwise it will show errors
    print("Connected to SQLite")
except sqlite3.Error as error:
    print("Failed to connect with sqlite3 database", error)
finally:
    # Inside Finally Block, If connection is open, we need to close it
    if sqliteConnection:
        # using close() method, we will close the connection
        sqliteConnection.close()
        # After closing connection object, we will print "the sqlite connection is closed"
        print("the sqlite connection is closed")


Output:

Image

Output for above python program



Similar Reads

Creating a sqlite database from CSV with Python
Prerequisites: PandasSQLite SQLite is a software library that implements a lightweight relational database management system. It does not require a server to operate unlike other RDBMS such as PostgreSQL, MySQL, Oracle, etc. and applications directly interact with a SQLite database. SQLite is often used for small applications, particularly in embed
2 min read
How to Create a Backup of a SQLite Database using Python?
In this article, we will learn How to Create a Backup of an SQLite Database using Python. To Create a Backup of an SQLite Database using Python, the required modules are SQLite3 and IO. First, let's create the original database to do that follow the below program: C/C++ Code import sqlite3 import io from sqlite3 import Error def SQLite_connection()
2 min read
How to connect to SQLite database that resides in the memory using Python ?
In this article, we will learn how to Connect an SQLite database connection to a database that resides in the memory using Python. But first let brief about what is sqlite. SQLite is a lightweight database software library that provides a relational database management system. Generally, it is a server-less database that can be used within almost a
3 min read
How to Show all Columns in the SQLite Database using Python ?
In this article, we will discuss how we can show all columns of a table in the SQLite database from Python using the sqlite3 module. Approach:Connect to a database using the connect() method.Create a cursor object and use that cursor object created to execute queries in order to create a table and insert values into it.Use the description keyword o
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() method.At this point, we create a cursor object to
3 min read
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. Approach: Importing necessary modulesRead data from CSV file DictReader()Establish a connection with the database.sqlit
2 min read
Python SQLite - Connecting to Database
In this article, we'll discuss how to connect to an SQLite Database using the sqlite3 module in Python. Connecting to the Database Connecting to the SQLite Database can be established using the connect() method, passing the name of the database to be accessed as a parameter. If that database does not exist, then it'll be created. sqliteConnection =
2 min read
Store Google Sheets data into SQLite Database using Python
In this article, we are going to store google sheets data into a database using python. The first step is to enable the API and to create the credentials, so let's get stared. Enabling the APIs and creating the credentialsGo to Marketplace in Cloud Console.Click on ENABLE APIS AND SERVICESThen Search for Google Drive API and enable itThen go to the
5 min read
Designing a RESTful API to interact with SQLite database
In this chapter, we will create Django API views for HTTP requests and will discuss how Django and Django REST framework process each HTTP request. Creating Django ViewsRouting URLs to Django views and functionsLaunching Django's development serverMaking HTTP requests using the command-line toolMaking HTTP requests with PostmanCreating Django Views
9 min read
Python VLC Instance - Creating new Media Instance
In this article we will see how we can create a Media instance from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance object we can creat
2 min read
How to create a new project in Django using Firebase Database?
Django is a Python-based web framework that allows you to quickly create efficient web applications. If you are new to Django then you can refer to Django Introduction and Installation. Here we are going to learn How to create a Django project using Firebase as Database . How to create a new project in Firebase ? Step 1: Firstly, We are going to Cr
3 min read
Python SQLite - Insert Data
In this article, we will discuss how can we insert data in a table in the SQLite database from Python using the sqlite3 module. The SQL INSERT INTO statement of SQL is used to insert a new row in a table. There are two ways of using the INSERT INTO statement for inserting rows: Only values: The first method is to specify only the value of data to b
3 min read
SQL using Python and SQLite | Set 2
Databases offer numerous functionalities by which one can manage large amounts of information easily over the web, and high-volume data input and output over a typical file such as a text file. SQL is a query language and is very popular in databases. Many websites use MySQL. SQLite is a "light" version that works over syntax very much similar to S
3 min read
Python SQLite - Update Data
In this article, we will discuss how we can update data in tables in the SQLite database using Python - sqlite3 module. The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple columns using UPDATE statement as per our requirement. Syntax: UPDATE table_name SET col
7 min read
Introduction to SQLite in Python
Databases offer numerous functionalities by which one can manage large amounts of information easily over the web and high-volume data input and output over a typical file such as a text file. SQL is a query language and is very popular in databases. Many websites use MySQL. SQLite is a "light" version that works over syntax very much similar to SQ
3 min read
Python SQLite - Update Specific Column
In this article, we will discuss how to update a specific column of a table in SQLite using Python. In order to update a particular column in a table in SQL, we use the UPDATE query. The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple columns using UPDATE stat
3 min read
How to store Python functions in a Sqlite table?
SQLite is a relational database system contained in a C library that works over syntax very much similar to SQL. It can be fused with Python with the help of the sqlite3 module. The Python Standard Library sqlite3 was developed by Gerhard Häring. It delivers an SQL interface compliant with the DB-API 2.0 specification described by PEP 249. To use t
3 min read
Python SQLite - JOIN Clause
In this article, we discuss the JOIN clause in SQLite using the sqlite3 module in Python. But at first let's see a brief about join in SQLite. Join Clause A JOIN clause combines the records from two tables on the basis of common attributes. The different types of joins are as follows: INNER JOIN (OR JOIN) - Gives the records that have common attrib
5 min read
Python SQLite - CRUD Operations
In this article, we will go through the CRUD Operation using the SQLite module in Python. CRUD Operations The abbreviation CRUD expands to Create, Read, Update and Delete. These four are fundamental operations in a database. In the sample database, we will create it, and do some operations. Let's discuss these operations one by one with the help of
4 min read
Python SQLite - Create Table
In this article, we will discuss how can we create tables in the SQLite database from the Python program using the sqlite3 module. In SQLite database we use the following syntax to create a table: CREATE TABLE database_name.table_name( column1 datatype PRIMARY KEY(one or more columns), column2 datatype, column3 datatype, ..... columnN datatype ); N
1 min read
SQLite Datatypes and its Corresponding Python Types
SQLite is a C-language-based library that provides a portable and serverless SQL database engine. It has a file-based architecture; hence it reads and writes to a disk. Since SQLite is a zero-configuration database, no installation or setup is needed before its usage. Starting from Python 2.5.x, SQLite3 comes default with python. In this article, w
3 min read
How to Delete a Specific Row from SQLite Table using Python ?
In this article, we will discuss how to delete of a specific row from the SQLite table using Python. In order to delete a particular row from a table in SQL, we use the DELETE query, The DELETE Statement in SQL is used to delete existing records from a table. We can delete a single record or multiple records depending on the condition we specify in
3 min read
How to Update all the Values of a Specific Column of SQLite Table using Python ?
In this article, we are going to update all the values of a specific column of a given SQLite table using Python. In order to update all the columns of a particular table in SQL, we use the UPDATE query. The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple colu
3 min read
Python SQLite - ORDER BY Clause
In this article, we will discuss ORDER BY clause in SQLite using Python. The ORDER BY statement is a SQL statement that is used to sort the data in either ascending or descending according to one or more columns. By default, ORDER BY sorts the data in ascending order. DESC is used to sort the data in descending order.ASC to sort in ascending order.
3 min read
Python SQLite - LIMIT Clause
In this article, we are going to discuss the LIMIT clause in SQLite using Python. But first, let's get a brief about the LIMIT clause. If there are many tuples satisfying the query conditions, it might be resourceful to view only a handful of them at a time. LIMIT keyword is used to limit the data given by the SELECT statement. Syntax: SELECT colum
2 min read
Python SQLite - DROP Table
In this article, we will discuss the DROP command in SQLite using Python. But first, let's get a brief about the drop command. DROP is used to delete the entire database or a table. It deleted both records in the table along with the table structure. Syntax: DROP TABLE TABLE_NAME; For dropping table, we will first create a database and a table in i
2 min read
Change SQLite Connection Timeout using Python
In this article, we will discuss how to change the SQLite connection timeout when connecting from Python. What is a connection timeout and what causes it? A connection timeout is an error that occurs when it takes too long for a server to respond to a user's request. Connection timeouts usually occur when there are multiple active connections to a
3 min read
Python SQLite - Deleting Data in Table
In this article, we will discuss how we can delete data in the table in the SQLite database from the Python program using the sqlite3 module. In SQLite database we use the following syntax to delete data from a table: DELETE FROM table_name [WHERE Clause] To create the database, we will execute the following code: C/C++ Code import sqlite3 # Connec
2 min read
How to Count the Number of Rows of a Given SQLite Table using Python?
In this article, we will discuss how we can count the number of rows of a given SQLite Table using Python. We will be using the cursor_obj.fetchall() method to do the same. This method fetches all the rows of a query result. It returns all the rows as a list of tuples. An empty list is returned if there is no record to fetch. To create the database
2 min read
How to Alter a SQLite Table using Python ?
In this article, we will discuss how can we alter tables in the SQLite database from a Python program using the sqlite3 module. We can do this by using ALTER statement. It allows to: Add one or more column to the tableChange the name of the table.Adding a column to a table The syntax of ALTER TABLE to add a new column in an existing table in SQLite
3 min read
Article Tags :
Practice Tags :