Python SQLite – Creating a New Database
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.
Similarly, we can create this database in python using the SQlite3 module.
Database Sqlite3.db formed.
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.
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")
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course