Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python sqlite3.connect() Function



The Python sqlite3.connect() function is used to create a connection in the SQLite database file. If the file doesn't exist in the existing database, then this function creates the connection automatically.

This function returns the connection object that is used to interact with the database. The sqlite3 module is independent of each function; each function in sqlite3 has a different connection object.

Syntax

Following is the basic syntax for the sqlite3.connect() function.

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

parameters

  • database: If the file doesn't exist, then it will be created.
  • timeout: The timeout for the database lock is released, with the default time of 0.5 seconds.

Return Value

The connection object returns the connection to the SQLite database.

Example 1

In the below example, we are going to demonstrate how to connect to an SQLite database by creating a table with specified columns and then we need to close the connection.

import sqlite3
conn = sqlite3.connect("sqlite.db")
conn.execute('''CREATE TABLE STUDENT(st_id INTEGER PRIMARY KEY, st_name VARCHAR(50), st_class VARCHAR(10), st_emal VARCHAR(30))''')
conn.close()

Output

This code creates a table and closes the connection.

Example 2

Here, we are connecting to an SQLite database, which executes a query to get the SQLite version and then closes the connection using the sqlite3.close() function.

import sqlite3 
connection = sqlite3.connect('res.db')
cursor = connection.cursor()
cursor.execute('SELECT SQKITE_VERSION()')
data = cursor.fetchone()
print(f'SQLite version:{data}')
connection.close()

Output

When we run the above code, we will get the following output −

SQLite version:('3.31.1')

Example 3

Now, we are going to connect() to an SQLite database with an incorrect timeout value, then this function throws TypeError.

import sqlite3
try:
   connection = sqlite3.connect('res.db',timeout='six')
except TyprError as e:
   print(f"TypeError:{e}")

Output

The output is generated as follows −

TypeError:must be real number, not str
python_modules.htm
Advertisements