Logo
Unit 6 – Working with Databases - SQLAlchemy

Working with Databases - SQLAlchemy

Duration: 5 minutes

Greetings, dedicated coders! Our journey into the depths of Python’s toolset continues as we venture into the domain of SQLAlchemy, a powerful SQL toolkit and Object-Relational Mapping (ORM) system for Python. In the realm of database interaction, SQL commands are inevitable. However, for those who find the SQL syntax cumbersome, ORM libraries like SQLAlchemy are a godsend. SQLAlchemy not only provides a full suite of well-known enterprise-level persistence patterns but also allows developers to utilize high-level SQL constructs with Pythonic idioms. Here’s a simple example of using SQLAlchemy to define a **‘User’ **class, create an SQLite database, add a user to the database, and query for the user:

from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy. orm import sessionmaker
from sqlalchemy. ext. declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
email = Column(String)
def main():
engine = create_engine('sqlite:///mydatabase. db')
Base. metadata. create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
new_user = User(name='John Doe', email='johndoe@example. com')
session. add(new_user)
session. commit()
user = session. query(User). filter_by(name='John Doe'). first()
print(user. email)
if __name__ == "__main__":
main()

Exercise

Your assignment, should you wish to undertake it:- Import the necessary components from SQLAlchemy.

  • Define a class mapping for a table in your database.
  • Create a connection to an SQLite database.
  • Initiate a session.
  • Use your session to add data to your table.
  • Use your session to query your table and print the result.

Conclusion

Bravo, Python maestro! You’ve descended into the strong world of ORMs, taking another step further in your Pythonic journey. Remember that SQLAlchemy isn’t simply a technique to avoid SQL; it’s also a tool for effective, streamlined database management, bringing Python’s philosophy of simplicity and readability to the table. Continue to practice and explore, and never lose your coding spirit!

Next Tutorial: Python and Web Development - Flask

5 minutes Minutes

Continue

Code on the Go with our Mobile App!

Unleash your coding potential anytime, anywhere!

Download Now!