
Play Store Application link – Java to Python in 17 Steps – App on Google Play
Github project link – https://github.com/kuldeep101990/Python_step13
As a Java developer, you’re probably familiar with JDBC (Java Database Connectivity), which allows Java applications to interact with databases. In Python, there are a number of ways to connect to and manipulate databases, and in this blog post, we’ll walk through two important database options: SQLite3 and MySQL. We’ll also explore ORMs like SQLAlchemy and compare them to Hibernate in Java.
By the end of this post, you’ll be able to understand how to use Python’s database connectivity libraries and perform common database operations, just like you would in Java. We’ll also provide code examples to help you get started right away.
1. Python’s sqlite3
vs. Java’s JDBC
SQLite3 in Python
Python comes with a built-in library called sqlite3, which provides a simple way to interact with SQLite databases. SQLite is a lightweight, file-based database engine that doesn’t require a server, making it a great choice for small-scale applications, prototyping, or embedded systems.
In Java, JDBC is used to connect to databases like MySQL, PostgreSQL, or even SQLite. It requires more boilerplate code, such as creating connection objects, managing exceptions, and performing queries manually. SQLite3, however, is straightforward and requires minimal setup.
Let’s see how to connect to a database in Python using sqlite3.
Python Example: Connecting to SQLite3
import sqlite3
# Connect to a SQLite database (or create it if it doesn't exist)
connection = sqlite3.connect('my_database.db')
# Create a cursor object to interact with the database
cursor = connection.cursor()
# Create a table (if it doesn't already exist)
cursor.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')
# Insert data into the table
cursor.execute("INSERT INTO users (name, age) VALUES ('John', 30)")
# Commit the transaction
connection.commit()
# Query the database
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
print(row)
# Close the connection
connection.close()
How it works:
- sqlite3.connect(‘my_database.db’) connects to (or creates) an SQLite database.
- We use a cursor object to execute SQL queries.
- After inserting data or making changes, we use
connection.commit()
to save those changes. - Finally, we query the data and loop through the results.
Java JDBC Example: Connecting to SQLite
Now let’s compare that to the JDBC approach in Java.
import java.sql.*;
public class Main {
public static void main(String[] args) {
try {
// Load the SQLite JDBC driver
Class.forName("org.sqlite.JDBC");
// Connect to the SQLite database
Connection conn = DriverManager.getConnection("jdbc:sqlite:my_database.db");
// Create a statement
Statement stmt = conn.createStatement();
// Create a table
stmt.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)");
// Insert data into the table
stmt.execute("INSERT INTO users (name, age) VALUES ('John', 30)");
// Query the database
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while (rs.next()) {
System.out.println(rs.getInt("id") + "\t" + rs.getString("name") + "\t" + rs.getInt("age"));
}
// Close the connection
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
How it works:
- DriverManager.getConnection is used to connect to the database in Java.
- We create a Statement object to execute SQL queries.
- Similar to Python’s
cursor.execute
, we use stmt.execute to run queries and manipulate data. - ResultSet is used to retrieve data, and we loop through the result to print it.
2. CRUD Operations in Python
Performing CRUD (Create, Read, Update, Delete) operations is a common task when working with databases. Let’s see how we can perform these operations in Python using sqlite3.
Create (Insert) Data
# Inserting new data into the 'users' table
cursor.execute("INSERT INTO users (name, age) VALUES ('Alice', 25)")
connection.commit()
Read (Select) Data
# Selecting all rows from the 'users' table
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
print(row)
Update Data
# Updating an existing record
cursor.execute("UPDATE users SET age = 26 WHERE name = 'Alice'")
connection.commit()
Delete Data
# Deleting a record
cursor.execute("DELETE FROM users WHERE name = 'Alice'")
connection.commit()
3. Using ORMs in Python (SQLAlchemy) vs. Java (Hibernate)
In Python, SQLAlchemy is a popular Object Relational Mapper (ORM). It allows you to interact with databases using Python classes instead of writing raw SQL queries, similar to how Hibernate works in Java. ORMs simplify the process of querying the database, reducing boilerplate code and improving code readability.
Let’s compare SQLAlchemy to Hibernate in Java:
- SQLAlchemy (Python): Allows developers to define classes that correspond to database tables and interact with the database using Python objects.
- Hibernate (Java): Provides similar functionality, mapping Java classes to database tables and allowing CRUD operations on these objects.
Here’s a basic example using SQLAlchemy in Python:
SQLAlchemy Setup for CRUD Operations
- Install SQLAlchemy:
pip install sqlalchemy
- Create a Python program using SQLAlchemy:
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# Define a base class
Base = declarative_base()
# Define a User class mapped to the 'users' table
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
# Create a SQLite database engine
engine = create_engine('sqlite:///my_database.db', echo=True)
# Create the 'users' table
Base.metadata.create_all(engine)
# Create a session to interact with the database
Session = sessionmaker(bind=engine)
session = Session()
# Create a new user
new_user = User(name='Bob', age=40)
session.add(new_user)
session.commit()
# Query all users
users = session.query(User).all()
for user in users:
print(f"{user.id} - {user.name} - {user.age}")
# Close the session
session.close()
How it works:
- SQLAlchemy’s
declarative_base()
creates a base class from which models (likeUser
) can inherit. engine
connects to the database, andsession
is used to interact with it.- We use
session.add
to add new records andsession.query
to query the database.
4. Complete Python Program with SQLite3 and SQLAlchemy
Now let’s wrap everything into a single Python script that does CRUD operations using both sqlite3 and SQLAlchemy, and includes checks to avoid inserting duplicate users.
import sqlite3
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# SQLite3 Example
print("Using sqlite3:")
# Connect to the SQLite database
connection = sqlite3.connect('my_database.db')
cursor = connection.cursor()
# Create a table if not already created
cursor.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')
# Check if user already exists before inserting
name = 'Alice'
age = 25
cursor.execute("SELECT * FROM users WHERE name = ? AND age = ?", (name, age))
existing_user = cursor.fetchall()
if existing_user:
print(f"User {name}, {age} already exists!")
else:
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", (name, age))
connection.commit()
print(f"User {name}, {age} added successfully!")
# Query all users from the database
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
print(row)
# Close the SQLite3 connection
connection.close()
# SQLAlchemy Example
print("\nUsing SQLAlchemy:")
Base = declarative_base()
# Define a User class that maps to the 'users' table
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
# Create an engine and session
engine = create_engine('sqlite:///my_database.db', echo=True)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
# Start an explicit transaction with the session
session = Session()
try:
# Check if user already exists in SQLAlchemy before inserting
existing_user = session.query(User).filter_by(name='Alice', age=25).first()
if existing_user:
print(f"User {name}, {age} already exists!")
else:
# Create a new user and add it to the session
new_user = User(name='Alice', age=25)
session.add(new_user)
session.commit() # Commit the transaction explicitly
print(f"User {name}, {age} added successfully!")
# Query all users in the SQLAlchemy database
users = session.query(User).all()
for user in users:
print(f"{user.id} - {user.name} - {user.age}")
# Commit all changes
session.commit()
except Exception as e:
print(f"Error: {e}")
session.rollback() # Rollback the transaction if any error occurs
finally:
# Close the session after all operations
session.close()
exists!”) else: # Create a new user and add it to the session new_user = User(name=’Alice’, age=25) session.add(new_user) session.commit() print(f”User {name}, {age} added successfully!”)
Query all users in the SQLAlchemy database
users = session.query(User).all() for user in users: print(f”{user.id} – {user.name} – {user.age}”)
Close the SQLAlchemy session
session.close()
### Conclusion
In this post, we've explored how to use **sqlite3** for direct SQL queries and **SQLAlchemy** for Object Relational Mapping (ORM) in Python. We also looked at how these Python approaches compare to **JDBC** and **Hibernate** in Java. By using these methods, you can easily integrate Python with databases, perform CRUD operations, and manage your data effectively, whether you're working with lightweight SQLite databases or full-scale relational systems.
Happy coding!
Hey there,
can you give me a call :
+1 775-522-8638
(My Ai Voice receptionist will answer the call)
Call now to see how voice AI can save your biz time and money.
Greetings
Dustin
Revolutionize your business with AI Bot Studio Lite! Automate customer interactions, answer important questions in real-time, close deals faster, and boost user engagement across websites, Facebook, Instagram, and WhatsApp—all without coding! Handle multiple conversations at once, personalize experiences, and never miss a lead again. Supports any language, provides instant support 24/7, and helps you stay ahead in the competitive market. Don’t miss out—this limited-time offer ends Sunday at midnight! Grab it now: https://sites.google.com/view/aibotstudio
Ever thought how corejava25hours.com could harness TikTok for genuine leads? Our AI-driven growth service targets the right users—based on hashtags they’re into and profiles they’re following—to supercharge your reach and push traffic back to you. We’ve had websites like yours see over 100 leads monthly.
Want to make TikTok work for corejava25hours.com? Test it out free for a week here: https://shorten.ee/kxzYW
Hello, I won’t waste your time—here’s the point:
Millions of people want to download their favorite YouTube videos and tunes but haven’t found a reliable website or app that does it without ads or viruses.
That’s why I built a minimalistic YouTube downloader for Windows, complete with all the essential features for effortless downloads.
Try my app, and I hope you’ll be 100% satisfied.
Download it here: https://youtubedownloaderforpc.com
P.S. The main goal behind launching this app is to eliminate spam ads and viruses, helping to keep the internet safe. If you like the app, please share it with your friends. If this message isn’t relevant to you, please ignore it, and I promise you won’t receive another email from me about it. Thanks for your understanding.
Get more leads for your corejava25hours.com website by using AI on Instagram. If you’re looking to drive more traffic, generate leads, and grow your brand’s reach, you can get more information and start a free trial here: https://cutt.ly/ErtvZbpG
This is an AI-powered Instagram growth service that:
-Increases followers with targeted, high-quality audiences.
-Boosts engagement through smart AI algorithms.
-Targets users based on hashtags and accounts they follow.
-Saves you time by automating tedious Instagram tasks.
Our service focuses on real, organic growth—no bots, no fake followers. It’s perfect for brands like yours that want to turn Instagram into a lead generation powerhouse. Better yet, our service is provided on a month-by-month subscription basis so you can cancel any time you like. No contracts and a 7 day free trial.
Every day, websites like corejava25hours.com fail to capture valuable traffic opportunities. Don’t let yours be one of them. Our smart traffic system is designed to increase exposure and bring real visitors to your site.
Claim your 4,000 free visitors to experience the benefits firsthand. Then, expand to plans offering up to 350K visitors per month. It’s time to realize your website’s true traffic potential. Get started here: https://shorten.ee/J-zRr
Are you dating someone, and would you like to know if they can be your best mate who will be romantically compatible with you? You can have a long-lasting romantic relationship and even a marriage. You can get precise answers to these questions in the ROMANTIC COMPATIBILITY report we can prepare for you and your potential mate. You will also get a RELATIONSHIPS report with more information about your relationship with your potential mate as a FREE bonus. You can order your ROMANTIC COMPATIBILITY report at https://wexxon.com/en/home/9-romantic-compatibility.html. We will add a RELATIONSHIPS report to your order as well.
Would you like this New Year to be the year you let go of your hurtful past? Make the resolution to make the change to become your Best Self.
Have you heard of Se-REM? (Self effective – Rapid Eye Movement). Many people don’t know that REM brain activity dramatically improves the processing of traumatic emotion. It creates peace and empowers the listener. Se-REM is an advanced version of EMDR therapy. It is more powerful because it combines elements of 6 different therapies, EMDR, hypnosis, mindfulness, Gestalt child within work, music therapy, and Awe therapy, (connecting profoundly with nature). Classical music alternates between the ears to enhance daydreaming and visualizing in ways you have never experienced. Please read the many reviews that express how much it has helped.
It has helped thousands of people overcome PTSD, and anxiety. But it is also helpful in a great many situations, any experience that has been traumatic. Se-REM’s mission statement is “Trauma relief at as close to free as possible”. This not-for-profit program downloads to a smart phone or computer and can be used at home.
Read and download at: Se-REM.com. Once you own the program, you are encouraged to give it away to others who will benefit.
Se-REM.com is in use in 33 countries