DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Build a Simple REST API Using Python Flask and SQLite (With Tests)
  • Manual Sharding in PostgreSQL: A Step-by-Step Implementation Guide
  • Python Packages for Validating Database Migration Projects
  • Database Query Service With OpenAI and PostgreSQL in .NET

Trending

  • Mastering Advanced Traffic Management in Multi-Cloud Kubernetes: Scaling With Multiple Istio Ingress Gateways
  • Navigating the LLM Landscape: A Comparative Analysis of Leading Large Language Models
  • Next-Gen IoT Performance Depends on Advanced Power Management ICs
  • Unlocking the Benefits of a Private API in AWS API Gateway
  1. DZone
  2. Data Engineering
  3. Databases
  4. An Overview of Creating Databases With Python

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.

By 
Joseph owino user avatar
Joseph owino
·
Feb. 13, 23 · Review
Likes (3)
Comment
Save
Tweet
Share
2.6K Views

Join the DZone community and get the full member experience.

Join For Free

Python 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:

Python
 
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:

Python
 
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:

Python
 
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:

Python
 
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:

Python
 
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.

Python
 
# 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:

Python
 
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.

Python
 
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.

Python
 
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. 

Database Python (language) Database application code style SQLite PostgreSQL

Opinions expressed by DZone contributors are their own.

Related

  • Build a Simple REST API Using Python Flask and SQLite (With Tests)
  • Manual Sharding in PostgreSQL: A Step-by-Step Implementation Guide
  • Python Packages for Validating Database Migration Projects
  • Database Query Service With OpenAI and PostgreSQL in .NET

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!