sqlite3
` module which comes pre-installed with Python. import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
password="mypassword"
)
print(mydb)​
import sqlite3
# Create a connection to the database
conn = sqlite3.connect('example.db')
# Create a cursor object to execute SQL statements
cursor = conn.cursor()
# Create a table
cursor.execute('''CREATE TABLE IF NOT EXISTS employees
(id INTEGER PRIMARY KEY, name TEXT, age INTEGER, salary REAL)''')
# Insert some data into the table
cursor.execute("INSERT INTO employees (name, age, salary) VALUES (?, ?, ?)", ('Alice', 25, 50000))
cursor.execute("INSERT INTO employees (name, age, salary) VALUES (?, ?, ?)", ('Bob', 30, 60000))
# Commit the changes
conn.commit()
# Close the connection
conn.close()
sqlite3
` module is imported at the beginning of the program. The `connect()
` function is then called to create a connection to a database file named `example.db
`. If the database file does not exist, it will be created.cursor()
` method of the connection object. This cursor object can be used to execute SQL statements on the database.employees
` using a SQL `CREATE TABLE
` statement. It then inserts some data into the table using SQL `INSERT
` statements.commit()
` method is called to commit the changes to the database. Finally, the connection is closed using the `close()
` method.IF NOT EXISTS
` clause is used in the `CREATE TABLE
` statement to ensure that the table is only created if it does not already exist. This prevents an error from occurring if the table has already been created in a previous run of the program.