[파이썬] 데이터베이스 연동과 ORM(Object-Relational Mapping)

Introduction

In modern web development, database integration plays a vital role in storing and retrieving data efficiently. Python offers various methods to connect to databases and interact with them. One common technique is to use Object-Relational Mapping (ORM), which allows developers to work with databases using Python objects.

In this blog post, we will explore how to connect to databases using Python and discuss the advantages of using ORM. We will also provide an example of implementing ORM in Python.

Connecting to Databases in Python

Python provides several libraries and modules to connect to different types of databases, such as MySQL, PostgreSQL, SQLite, and more. Some popular choices include MySQLdb, psycopg2, and sqlite3.

To connect to a database, you need to install the relevant library/module and import it into your Python script. Then, you can establish a connection by providing the necessary connection parameters, such as host, database, username, and password. Once the connection is established, you can execute SQL queries and retrieve data.

Here’s an example of connecting to a MySQL database using the MySQLdb library:

import MySQLdb

# Establish connection
conn = MySQLdb.connect(host="localhost", user="root", password="password", database="mydb")

# Create a cursor
cursor = conn.cursor()

# Execute a query
cursor.execute("SELECT * FROM users")

# Fetch all rows
rows = cursor.fetchall()

# Print the results
for row in rows:
    print(row)

# Close the connection
conn.close()

Introduction to Object-Relational Mapping (ORM)

ORM is a technique that allows developers to interact with databases using high-level programming objects instead of writing complex SQL queries. It provides a convenient way to map database tables to Python classes and performs CRUD operations (Create, Read, Update, Delete) seamlessly.

ORM libraries provide a set of APIs and methods to perform database operations using Python objects. One popular ORM library in Python is SQLAlchemy. It supports various databases and provides a powerful and flexible interface for working with databases.

Using ORM in Python with SQLAlchemy

To use ORM in Python, you need to install the SQLAlchemy library. You can install it using pip:

pip install SQLAlchemy

Once installed, you can import SQLAlchemy in your Python script and define your database models as Python classes. Each class represents a table in the database, and each attribute of the class represents a column.

Here’s an example of using SQLAlchemy ORM to define a User model:

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    email = Column(String(100))

    def __repr__(self):
        return f"<User(id={self.id}, name={self.name}, email={self.email})>"

In the above example, we have defined a User model that corresponds to the users table in the database. We specify the table name using the __tablename__ attribute, and then define individual columns using the Column class. We also define a __repr__ method for a readable representation of the User object.

To interact with the database, we need to establish a connection and create a session. Then, we can use the session to perform CRUD operations on our User model.

Here’s an example of using SQLAlchemy ORM to query the User model:

from sqlalchemy.orm import sessionmaker

# Establish connection
engine = create_engine("sqlite:///mydatabase.db")
Session = sessionmaker(bind=engine)
session = Session()

# Query all users
users = session.query(User).all()

# Print the results
for user in users:
    print(user)

# Close the session
session.close()

In the above example, we create an engine by specifying the database URL (sqlite:///mydatabase.db). We then create a session using the sessionmaker class and bind it to the engine. Finally, we can query the User model using the session and retrieve all users from the database.

Conclusion

Connecting to databases and interacting with them is an essential part of web development. Python offers various methods to connect to databases, and using ORM simplifies the process by allowing developers to work with databases using Python objects.

In this blog post, we explored how to connect to databases in Python and discussed the advantages of using ORM. We also provided an example of implementing ORM using SQLAlchemy.

Using ORM can make database operations more manageable, maintainable, and scalable. It abstracts away the complexity of SQL queries and allows developers to focus on their application logic.

So, next time you need to work with databases in Python, consider using ORM and enjoy the benefits it offers!