Google News
logo
Python Program to Create a connection to a database
To create a connection to a database in Python, you can use the `sqlite3` module which comes pre-installed with Python.

Here's an example Python program that creates a connection to an SQLite database :

example.db :
import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="myusername",
  password="mypassword"
)

print(mydb)​
Program :
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()
In this example, the `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.

Next, a cursor object is created using the `cursor()` method of the connection object. This cursor object can be used to execute SQL statements on the database.

In this example, the program creates a table named `employees` using a SQL `CREATE TABLE` statement. It then inserts some data into the table using SQL `INSERT` statements.

After the changes have been made, the `commit()` method is called to commit the changes to the database. Finally, the connection is closed using the `close()` method.

Note that in this example, the `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.