An Overview of Creating Databases With Python
This article shows how to construct, change, and manage databases effectively and efficiently with a basic understanding of Python language and SQL syntax.
Join the DZone community and get the full member experience.
Join For FreePython provides several modules for working with databases, including sqlite3, MySQLdb, and psycopg2. These modules allow easy database interaction to store, retrieve, and manipulate data efficiently. You can construct, change, and manage databases effectively and efficiently with a basic understanding of Python language and SQL syntax.
Steps for Database Creation Using Python
Step 1
Install a database adapter that matches the database management system you want to use. For example, if you are to use SQLite, you can install the sqlite3 module. For MySQL, you can install the MySQLdb module, and for PostgreSQL, you can install psycopg2. In this tutorial, we shall consider SQLite, MongoDB, and MySQLdb. To use SQLite in your Python code, import the sqlite3 module:
import sqlite3
Once you have installed the appropriate module, you need to create a connection to the database, which serves as a bridge between the Python code and the database, allowing you to send commands and receive results. For example, in SQLite, you can create a connection using the following code.
For an example of a database called school.db, you connect as shown in the code below:
conn = sqlite3.connect('school.db')
Step 2
Create tables in the database. To create tables in a database, you'll need to write SQL statements using the cursor object obtained from the connection. For example, to create a table named "employees" with columns "id," "username," salary, department, and "email," you use the following code:
conn = sqlite3.connect('school.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
username TEXT,
email,
salary REAL,
department TEXT
)
''')
Step 3
Insert, update, and retrieve data from the database using SQL commands and the cursor object. To add data to the tables, you can use the "INSERT INTO" SQL statement. Save the data using the `commit()` method. For example, the following code inserts data into the "employees" table:
conn = sqlite3.connect('school.db')
cursor = conn.cursor()
cursor.execute("INSERT INTO employees (username, email, salary, department) VALUES ('Joseph', 'joseph@gmail,com' 70000, 'IT')")
conn.commit()
Step 4
Retrieve data from the tables. To retrieve data from the tables, you can use the "SELECT" SQL statement. For example, to retrieve all the users from the "users" table, you can use the following code:
cursor.execute("SELECT * FROM employees")
rows = cursor.fetchall()
for row in rows:
print(row)
Step 5
Create views by executing a CREATE VIEW statement, and use the `execute()` method of the cursor object to execute a CREATE VIEW statement.
# Execute the CREATE VIEW statement
cursor.execute('''
CREATE VIEW employees_view AS
SELECT name, age, department, email, FROM employees;
''')
Step 6
Close the connection. Once you're done working with the database, it's important to close the connection to free up the resources. You can close the connection by using the close() method of the connection object. For example:
conn.commit()
conn.close()
Sample for MySQLdb
To create a database in MySQLdb, import the MYSQLdb module and connect to the database using the `connect()` method. You can create a cursor and use it to execute SQL commands. The `execute ()` method is used to create a table and insert data into it. After committing the changes, we use the cursor to select data from the table and fetch all the data using the `fetchall()` method. And finally, close the cursor and connection to the database.
import MySQLdb
# Connect to the database
conn = MySQLdb.connect(host="localhost", user="std", passwd="@12343!J", db="school.db")
# Create a cursor to execute SQL commands
cursor = conn.cursor()
# Create a table
cursor.execute("""
CREATE TABLE employees (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
salary DECIMAL(10,2),
department VARCHAR(255)
)
""")
# Insert data into the table
cursor.execute("""
INSERT INTO employees (name, salary, department)
VALUES
("Joseph", 70000, "IT"),
("Jane", 80000, "Marketing")
""")
# Commit the changes to the database
conn.commit()
# Select data from the table
cursor.execute("SELECT * FROM employees")
# Fetch all the data
employees = cursor.fetchall()
# Print the data
for employee in employees:
print(employee)
# Close the cursor and connection
cursor.close()
conn.close()
Sample for MongoDB
Import the pymongo module and connect to the database using the `MongoClient()` class. You then get a reference to the database and the collection equivalent to a table in SQL. The `inser _many()` method is used to insert data into the collection. The `find()` method is used to query data from the collection, and the data is fetched using a for loop. And finally, close the connection to the database using the `close()` method.
from pymongo import MongoClient
# Connect to the database
client = MongoClient("mongodb://localhost:27017/")
# Get a reference to the database
db = client["school.db"]
# Get a reference to the collection (equivalent to a table in SQL)
collection = db["employees"]
# Insert data into the collection
employee1 = { "name": "Joseph", "salary": 70000, "department": "IT" }
employee2 = { "name": "Jane", "salary": 80000, "department": "Marketing" }
collection.insert_many([employee1, employee2])
# Query data from the collection
employees = collection.find()
# Print the data
for employee in employees:
print(employee)
# Close the connection
client.close()
Conclusion
In conclusion, Python provides several modules to interact with different databases, such as MySQL and MongoDB. The MySQLdb module is used to interact with a MySQL database, and the pymongo module is used to interact with a MongoDB database. Both modules make it easy for developers to perform common database operations such as creating tables, inserting data, querying data, and more. With Python's simplicity and ease of use, it has become a popular choice for developing database-driven applications. Whether you're a beginner or an experienced developer, using these modules will make working with databases in Python a breeze.
Opinions expressed by DZone contributors are their own.
Comments