{"id":18401,"date":"2024-07-16T23:56:36","date_gmt":"2024-07-17T06:56:36","guid":{"rendered":"https:\/\/www.pingcap.com\/article\/sqlalchemy-tutorial-practical-examples-for-python-coders\/"},"modified":"2024-12-12T02:03:50","modified_gmt":"2024-12-12T10:03:50","slug":"sqlalchemy-tutorial-practical-examples-for-python-coders","status":"publish","type":"article","link":"https:\/\/www.pingcap.com\/ko\/article\/sqlalchemy-tutorial-practical-examples-for-python-coders\/","title":{"rendered":"SQLAlchemy Tutorial: Practical Examples for Python Coders"},"content":{"rendered":"\n<p>SQLAlchemy is a powerful Python library that simplifies database interactions by allowing developers to work with SQL databases using Python objects. Its significance in Python development cannot be overstated, as it provides a robust toolkit for managing relational databases efficiently. This tutorial emphasizes practical SQLAlchemy examples to enhance your learning experience. Whether you&#8217;re a novice or an experienced Python developer, this guide aims to equip you with the skills needed to leverage SQLAlchemy effectively in your projects.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Getting_Started_with_SQLAlchemy\"><\/span>Getting Started with SQLAlchemy<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">What is SQLAlchemy?<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">Overview of SQLAlchemy<\/h4>\n\n\n\n<p><strong>SQLAlchemy<\/strong> is a versatile and powerful Python library designed to facilitate seamless interaction with relational databases. It provides a high-level abstraction layer known as the Object-Relational Mapping (ORM), which allows developers to work with databases using Python objects and methods instead of raw SQL queries. This abstraction not only simplifies database operations but also enhances code readability and maintainability.<\/p>\n\n\n\n<p>At its core, SQLAlchemy bridges the gap between Python applications and SQL databases, enabling developers to perform complex database operations with minimal effort. Whether you&#8217;re building a small application or managing a large-scale system, SQLAlchemy offers the tools you need to efficiently handle your database interactions.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Key Features and Benefits<\/h4>\n\n\n\n<p>SQLAlchemy boasts a plethora of features that make it an indispensable tool for Python developers:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>ORM Layer<\/strong>: The ORM layer abstracts the complexities of SQL, allowing developers to interact with the database using Python classes and objects.<\/li>\n\n\n\n<li><strong>Flexibility<\/strong>: SQLAlchemy supports multiple database backends, including MySQL, PostgreSQL, SQLite, and TiDB, making it a versatile choice for various projects.<\/li>\n\n\n\n<li><strong>Comprehensive Querying<\/strong>: With SQLAlchemy, you can execute both simple and complex queries, including joins, aggregations, and subqueries, using a Pythonic syntax.<\/li>\n\n\n\n<li><strong>Connection Management<\/strong>: It provides robust connection pooling and transaction management, ensuring efficient and reliable database interactions.<\/li>\n\n\n\n<li><strong>Extensibility<\/strong>: SQLAlchemy is highly extensible, allowing developers to customize and extend its functionality to meet specific project requirements.<\/li>\n<\/ul>\n\n\n\n<p>These features collectively empower developers to build scalable, maintainable, and efficient database-driven applications.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Installation and Setup<\/h3>\n\n\n\n<p>Getting started with SQLAlchemy involves a few straightforward steps to set up your development environment.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Installing SQLAlchemy<\/h4>\n\n\n\n<p>To install SQLAlchemy, you can use <code>pip<\/code>, the Python package installer. Open your terminal and run the following command:<\/p>\n\n\n\n<pre class=\"wp-block-code\">\n<code class=\"language-bash\">pip install SQLAlchemy\n<\/code>\n<\/pre>\n\n\n\n<p>This command will download and install the latest version of SQLAlchemy from the Python Package Index (PyPI).<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Setting Up a Virtual Environment<\/h4>\n\n\n\n<p>It&#8217;s a best practice to create a virtual environment for your project to manage dependencies and avoid conflicts with other projects. You can create a virtual environment using the <code>venv<\/code> module included with Python. Run the following commands in your terminal:<\/p>\n\n\n\n<pre class=\"wp-block-code\">\n<code class=\"language-bash\">python -m venv myenv\nsource myenv\/bin\/activate  # On Windows, use `myenvScriptsactivate`\n<\/code>\n<\/pre>\n\n\n\n<p>This will create and activate a virtual environment named <code>myenv<\/code>.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Basic Configuration<\/h4>\n\n\n\n<p>Once you have SQLAlchemy installed and your virtual environment set up, you need to configure your database connection. For this example, we&#8217;ll use a TiDB database. First, install the necessary database driver, such as <code>PyMySQL<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\">\n<code class=\"language-bash\">pip install PyMySQL\n<\/code>\n<\/pre>\n\n\n\n<p>Next, create a Python script to define your database connection. Here&#8217;s a basic example:<\/p>\n\n\n\n<pre class=\"wp-block-code\">\n<code class=\"language-python\">from sqlalchemy import create_engine\n# Replace with your actual database credentials\nDATABASE_URI = 'mysql+pymysql:\/\/username:password@host:port\/database'\nengine = create_engine(DATABASE_URI)\n<\/code>\n<\/pre>\n\n\n\n<p>In this script, replace <code>username<\/code>, <code>password<\/code>, <code>host<\/code>, <code>port<\/code>, and <code>database<\/code> with your actual TiDB database credentials. The <code>create_engine<\/code> function initializes a connection to the database using the specified URI.<\/p>\n\n\n\n<p>With these steps, you have successfully installed SQLAlchemy, set up a virtual environment, and configured a basic connection to your TiDB database. You&#8217;re now ready to dive deeper into SQLAlchemy&#8217;s capabilities and start building robust database-driven applications.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Core_Concepts_of_SQLAlchemy\"><\/span>Core Concepts of SQLAlchemy<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">SQLAlchemy ORM<\/h3>\n\n\n\n<p>The Object-Relational Mapping (ORM) layer is one of the most compelling features of SQLAlchemy. It allows developers to interact with databases using Python classes and objects, abstracting away the complexities of raw SQL queries.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Understanding ORM<\/h4>\n\n\n\n<p>At its essence, ORM is a technique that converts data between incompatible systems\u2014in this case, between Python objects and relational database tables. By using ORM, you can perform database operations without writing explicit SQL queries. This not only simplifies the code but also makes it more readable and maintainable.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>&#8220;ORMs provide a high-level abstraction upon a relational database, allowing developers to work with data in an object-oriented manner.&#8221;<\/p>\n<\/blockquote>\n\n\n\n<p>SQLAlchemy&#8217;s ORM is particularly powerful because it offers both flexibility and control, enabling developers to fine-tune their database interactions as needed.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Defining Models<\/h4>\n\n\n\n<p>In SQLAlchemy, models are Python classes that map to database tables. Each attribute of the class corresponds to a column in the table. Here&#8217;s an example of how to define a model for a <code>Player<\/code> table:<\/p>\n\n\n\n<pre class=\"wp-block-code\">\n<code class=\"language-python\">from sqlalchemy import Column, Integer, String\nfrom sqlalchemy.orm import declarative_base\nBase = declarative_base()\nclass Player(Base):\n    __tablename__ = 'players'\n    id = Column(Integer, primary_key=True)\n    name = Column(String(32), unique=True)\n    coins = Column(Integer)\n    goods = Column(Integer)\n<\/code>\n<\/pre>\n\n\n\n<p>In this example, the <code>Player<\/code> class defines a model with four columns: <code>id<\/code>, <code>name<\/code>, <code>coins<\/code>, and <code>goods<\/code>. The <code>__tablename__<\/code> attribute specifies the name of the table in the database.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Creating Tables<\/h4>\n\n\n\n<p>Once you&#8217;ve defined your models, you can create the corresponding tables in the database. This is done using the <code>create_all<\/code> method on the <code>Base<\/code> class:<\/p>\n\n\n\n<pre class=\"wp-block-code\">\n<code class=\"language-python\">from sqlalchemy import create_engine\n# Replace with your actual database credentials\nDATABASE_URI = 'mysql+pymysql:\/\/username:password@host:port\/database'\nengine = create_engine(DATABASE_URI)\nBase.metadata.create_all(engine)\n<\/code>\n<\/pre>\n\n\n\n<p>This script will create the <code>players<\/code> table in your TiDB database if it doesn&#8217;t already exist. The <code>create_all<\/code> method ensures that all tables defined by your models are created.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">SQLAlchemy Core<\/h3>\n\n\n\n<p>While the ORM layer provides a high-level abstraction, SQLAlchemy Core offers a lower-level interface for interacting with the database. This gives developers more control over SQL execution and is useful for complex queries or performance optimizations.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">SQL Expression Language<\/h4>\n\n\n\n<p>The SQL Expression Language is a powerful feature of SQLAlchemy Core that allows you to construct SQL queries using Python expressions. Here&#8217;s an example of how to create a simple query:<\/p>\n\n\n\n<pre class=\"wp-block-code\">\n<code class=\"language-python\">from sqlalchemy import select, Table, MetaData\nmetadata = MetaData()\nplayers = Table('players', metadata, autoload_with=engine)\nquery = select(players).where(players.c.name == 'test')\n<\/code>\n<\/pre>\n\n\n\n<p>In this example, the <code>select<\/code> function constructs a SQL SELECT statement, and the <code>where<\/code> method adds a condition to filter the results.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Executing Queries<\/h4>\n\n\n\n<p>To execute queries, you use the <code>execute<\/code> method on the connection object. Here&#8217;s how you can run the query defined above:<\/p>\n\n\n\n<pre class=\"wp-block-code\">\n<code class=\"language-python\">with engine.connect() as connection:\n    result = connection.execute(query)\n    for row in result:\n        print(row)\n<\/code>\n<\/pre>\n\n\n\n<p>This script connects to the database, executes the query, and prints the results. The <code>with<\/code> statement ensures that the connection is properly closed after the operation.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Connection Management<\/h4>\n\n\n\n<p>Efficient connection management is crucial for the performance and reliability of your application. SQLAlchemy provides robust tools for managing connections, including connection pooling and transaction management.<\/p>\n\n\n\n<p>Connection pooling helps to reuse database connections, reducing the overhead of establishing new connections. You can configure connection pooling when creating the engine:<\/p>\n\n\n\n<pre class=\"wp-block-code\">\n<code class=\"language-python\">engine = create_engine(DATABASE_URI, pool_size=10, max_overflow=20)\n<\/code>\n<\/pre>\n\n\n\n<p>In this example, <code>pool_size<\/code> sets the number of connections to keep in the pool, and <code>max_overflow<\/code> specifies the maximum number of connections that can be created beyond the pool size.<\/p>\n\n\n\n<p>By understanding and leveraging these core concepts of SQLAlchemy, you can build efficient, scalable, and maintainable database-driven applications.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Practical_Examples_with_SQLAlchemy\"><\/span>Practical Examples with SQLAlchemy<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In this section, we will delve into practical SQLAlchemy examples that demonstrate how to perform essential database operations. These examples will help you understand how to leverage SQLAlchemy effectively in your Python projects.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Basic CRUD Operations<\/h3>\n\n\n\n<p>CRUD stands for Create, Read, Update, and Delete\u2014four fundamental operations for managing data in a database. Let&#8217;s explore how to perform these operations using SQLAlchemy.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Creating Records<\/h4>\n\n\n\n<p>To create records in your database, you need to instantiate your model class and add it to the session. Here&#8217;s an example of how to create a new <code>Player<\/code> record:<\/p>\n\n\n\n<pre class=\"wp-block-code\">\n<code class=\"language-python\">from sqlalchemy.orm import sessionmaker\nSession = sessionmaker(bind=engine)\nsession = Session()\nnew_player = Player(name=\"Alice\", coins=150, goods=200)\nsession.add(new_player)\nsession.commit()\n<\/code>\n<\/pre>\n\n\n\n<p>In this example, we create a new <code>Player<\/code> object and add it to the session. The <code>commit<\/code> method saves the changes to the database.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Reading Records<\/h4>\n\n\n\n<p>Reading records involves querying the database to retrieve data. SQLAlchemy provides a powerful querying interface to accomplish this:<\/p>\n\n\n\n<pre class=\"wp-block-code\">\n<code class=\"language-python\">players = session.query(Player).all()\nfor player in players:\n    print(player.name, player.coins, player.goods)\n<\/code>\n<\/pre>\n\n\n\n<p>This script retrieves all records from the <code>players<\/code> table and prints their details. You can also filter records based on specific criteria:<\/p>\n\n\n\n<pre class=\"wp-block-code\">\n<code class=\"language-python\">player = session.query(Player).filter_by(name=\"Alice\").first()\nprint(player.name, player.coins, player.goods)\n<\/code>\n<\/pre>\n\n\n\n<p>Here, we use the <code>filter_by<\/code> method to find the player named &#8220;Alice&#8221;.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Updating Records<\/h4>\n\n\n\n<p>Updating records is straightforward with SQLAlchemy. You first query the record you want to update, modify its attributes, and commit the changes:<\/p>\n\n\n\n<pre class=\"wp-block-code\">\n<code class=\"language-python\">player = session.query(Player).filter_by(name=\"Alice\").first()\nplayer.coins += 50\nsession.commit()\n<\/code>\n<\/pre>\n\n\n\n<p>In this example, we increase Alice&#8217;s coins by 50 and save the updated record to the database.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Deleting Records<\/h4>\n\n\n\n<p>Deleting records involves querying the record you want to remove and then deleting it from the session:<\/p>\n\n\n\n<pre class=\"wp-block-code\">\n<code class=\"language-python\">player = session.query(Player).filter_by(name=\"Alice\").first()\nsession.delete(player)\nsession.commit()\n<\/code>\n<\/pre>\n\n\n\n<p>This script deletes the player named &#8220;Alice&#8221; from the database.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Advanced Query Techniques<\/h3>\n\n\n\n<p>SQLAlchemy offers advanced querying capabilities that allow you to perform complex database operations efficiently.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Filtering and Sorting<\/h4>\n\n\n\n<p>Filtering and sorting records can be done using the <code>filter<\/code> and <code>order_by<\/code> methods:<\/p>\n\n\n\n<pre class=\"wp-block-code\">\n<code class=\"language-python\">players = session.query(Player).filter(Player.coins &gt; 100).order_by(Player.name).all()\nfor player in players:\n    print(player.name, player.coins)\n<\/code>\n<\/pre>\n\n\n\n<p>This query retrieves players with more than 100 coins and sorts them by name.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Joins and Relationships<\/h4>\n\n\n\n<p>SQLAlchemy makes it easy to work with related tables using joins. Suppose we have another table called <code>Team<\/code> and we want to join it with the <code>Player<\/code> table:<\/p>\n\n\n\n<pre class=\"wp-block-code\">\n<code class=\"language-python\">from sqlalchemy.orm import relationship\nclass Team(Base):\n    __tablename__ = 'teams'\n    id = Column(Integer, primary_key=True)\n    name = Column(String(32), unique=True)\n    players = relationship(\"Player\", back_populates=\"team\")\nPlayer.team_id = Column(Integer, ForeignKey('teams.id'))\nPlayer.team = relationship(\"Team\", back_populates=\"players\")\n<\/code>\n<\/pre>\n\n\n\n<p>Now, you can perform a join query:<\/p>\n\n\n\n<pre class=\"wp-block-code\">\n<code class=\"language-python\">teams_with_players = session.query(Team).join(Player).all()\nfor team in teams_with_players:\n    print(team.name, [player.name for player in team.players])\n<\/code>\n<\/pre>\n\n\n\n<p>This query retrieves teams and their associated players.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Aggregations and Grouping<\/h4>\n\n\n\n<p>Aggregations and grouping are essential for summarizing data. SQLAlchemy supports these operations through functions like <code>func<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\">\n<code class=\"language-python\">from sqlalchemy import func\nplayer_count = session.query(func.count(Player.id)).scalar()\nprint(f\"Total players: {player_count}\")\ncoins_sum = session.query(func.sum(Player.coins)).scalar()\nprint(f\"Total coins: {coins_sum}\")\n<\/code>\n<\/pre>\n\n\n\n<p>These queries count the total number of players and sum the total coins, respectively.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Working with Transactions<\/h3>\n\n\n\n<p>Transactions ensure that a series of database operations are executed atomically. SQLAlchemy provides robust transaction management features.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Transaction Management<\/h4>\n\n\n\n<p>You can manage transactions using the <code>begin<\/code> method:<\/p>\n\n\n\n<pre class=\"wp-block-code\">\n<code class=\"language-python\">with engine.begin() as connection:\n    connection.execute(query1)\n    connection.execute(query2)\n<\/code>\n<\/pre>\n\n\n\n<p>This ensures that both queries are executed within a single transaction.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Handling Rollbacks<\/h4>\n\n\n\n<p>In case of an error, you can roll back the transaction to maintain data integrity:<\/p>\n\n\n\n<pre class=\"wp-block-code\">\n<code class=\"language-python\">try:\n    with engine.begin() as connection:\n        connection.execute(query1)\n        connection.execute(query2)\nexcept Exception as e:\n    print(f\"Transaction failed: {e}\")\n    session.rollback()\n<\/code>\n<\/pre>\n\n\n\n<p>This script rolls back the transaction if any of the queries fail.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Savepoints<\/h4>\n\n\n\n<p>Savepoints allow you to roll back part of a transaction without affecting the entire transaction:<\/p>\n\n\n\n<pre class=\"wp-block-code\">\n<code class=\"language-python\">with session.begin_nested():\n    session.add(player1)\n    session.flush()  # Savepoint created here\n    session.add(player2)\n    session.rollback()  # Rolls back to the savepoint\n<\/code>\n<\/pre>\n\n\n\n<p>In this example, only the addition of <code>player2<\/code> is rolled back, while <code>player1<\/code> remains in the session.<\/p>\n\n\n\n<p>By mastering these practical SQLAlchemy examples, you can efficiently manage your database operations and build robust, scalable applications.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Integrating_SQLAlchemy_with_Flask\"><\/span>Integrating SQLAlchemy with Flask<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Flask is a lightweight web framework for Python that makes it easy to build web applications. When combined with SQLAlchemy, Flask becomes a powerful tool for creating dynamic, database-driven web applications. In this section, we&#8217;ll walk through the process of setting up Flask with SQLAlchemy and building a simple web application.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Setting Up Flask with SQLAlchemy<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">Installing Flask-SQLAlchemy<\/h4>\n\n\n\n<p>To get started, you&#8217;ll need to install Flask and Flask-SQLAlchemy. Flask-SQLAlchemy is an extension that adds SQLAlchemy support to your Flask application. You can install both packages using <code>pip<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\">\n<code class=\"language-bash\">pip install Flask Flask-SQLAlchemy\n<\/code>\n<\/pre>\n\n\n\n<p>This command will install Flask and Flask-SQLAlchemy, along with their dependencies.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Configuring the Application<\/h4>\n\n\n\n<p>Once you have Flask and Flask-SQLAlchemy installed, you need to configure your Flask application to use SQLAlchemy. Here&#8217;s a basic example of how to set up your application:<\/p>\n\n\n\n<pre class=\"wp-block-code\">\n<code class=\"language-python\">from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql:\/\/username:password@host:port\/database'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\ndb = SQLAlchemy(app)\n<\/code>\n<\/pre>\n\n\n\n<p>In this script, replace <code>username<\/code>, <code>password<\/code>, <code>host<\/code>, <code>port<\/code>, and <code>database<\/code> with your actual TiDB database credentials. The <code>SQLALCHEMY_DATABASE_URI<\/code> configuration tells Flask-SQLAlchemy how to connect to your database. The <code>SQLALCHEMY_TRACK_MODIFICATIONS<\/code> setting is optional but recommended to disable to avoid overhead.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Building a Simple Web Application<\/h3>\n\n\n\n<p>With Flask and SQLAlchemy configured, you&#8217;re ready to build a simple web application. We&#8217;ll cover defining routes and views, handling forms and user input, and displaying data from the database.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Defining Routes and Views<\/h4>\n\n\n\n<p>Routes and views are the core components of a Flask application. Routes define the URLs that your application will respond to, and views define the logic for handling those requests. Here&#8217;s an example of a simple route and view:<\/p>\n\n\n\n<pre class=\"wp-block-code\">\n<code class=\"language-python\">@app.route('\/')\ndef index():\n    return \"Hello, World!\"\n<\/code>\n<\/pre>\n\n\n\n<p>This route responds to requests to the root URL (<code>\/<\/code>) and returns a simple &#8220;Hello, World!&#8221; message.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Handling Forms and User Input<\/h4>\n\n\n\n<p>To handle forms and user input, you&#8217;ll need to create HTML templates and define routes that process the form data. Here&#8217;s an example of a route that displays a form and another route that processes the form submission:<\/p>\n\n\n\n<pre class=\"wp-block-code\">\n<code class=\"language-python\">from flask import request, render_template\n@app.route('\/add_player', methods=['GET', 'POST'])\ndef add_player():\n    if request.method == 'POST':\n        name = request.form['name']\n        coins = request.form['coins']\n        goods = request.form['goods']\n        new_player = Player(name=name, coins=coins, goods=goods)\n        db.session.add(new_player)\n        db.session.commit()\n        return \"Player added successfully!\"\n    return render_template('add_player.html')\n<\/code>\n<\/pre>\n\n\n\n<p>In this example, the <code>\/add_player<\/code> route handles both GET and POST requests. For GET requests, it renders a form template (<code>add_player.html<\/code>). For POST requests, it processes the form data, creates a new <code>Player<\/code> object, and saves it to the database.<\/p>\n\n\n\n<p>Here&#8217;s a simple HTML form template (<code>add_player.html<\/code>):<\/p>\n\n\n\n<pre class=\"wp-block-code\">\n<code class=\"language-html\">&lt;!doctype html&gt;\n&lt;html lang=\"en\"&gt;\n  &lt;head&gt;\n    &lt;meta charset=\"utf-8\"&gt;\n    &lt;title&gt;Add Player&lt;\/title&gt;\n  &lt;\/head&gt;\n  &lt;body&gt;\n    &lt;form method=\"post\"&gt;\n      Name: &lt;input type=\"text\" name=\"name\"&gt;&lt;br&gt;\n      Coins: &lt;input type=\"number\" name=\"coins\"&gt;&lt;br&gt;\n      Goods: &lt;input type=\"number\" name=\"goods\"&gt;&lt;br&gt;\n      &lt;input type=\"submit\" value=\"Add Player\"&gt;\n    &lt;\/form&gt;\n  &lt;\/body&gt;\n&lt;\/html&gt;\n<\/code>\n<\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Displaying Data from the Database<\/h4>\n\n\n\n<p>To display data from the database, you&#8217;ll need to query the database and pass the results to a template. Here&#8217;s an example of a route that retrieves all players from the database and displays them in a template:<\/p>\n\n\n\n<pre class=\"wp-block-code\">\n<code class=\"language-python\">@app.route('\/players')\ndef show_players():\n    players = Player.query.all()\n    return render_template('show_players.html', players=players)\n<\/code>\n<\/pre>\n\n\n\n<p>And here&#8217;s a simple HTML template (<code>show_players.html<\/code>) to display the players:<\/p>\n\n\n\n<pre class=\"wp-block-code\">\n<code class=\"language-html\">&lt;!doctype html&gt;\n&lt;html lang=\"en\"&gt;\n  &lt;head&gt;\n    &lt;meta charset=\"utf-8\"&gt;\n    &lt;title&gt;Players&lt;\/title&gt;\n  &lt;\/head&gt;\n  &lt;body&gt;\n    &lt;h1&gt;Players&lt;\/h1&gt;\n    &lt;ul&gt;\n      {% for player in players %}\n        &lt;li&gt;{{ player.name }}: {{ player.coins }} coins, {{ player.goods }} goods&lt;\/li&gt;\n      {% endfor %}\n    &lt;\/ul&gt;\n  &lt;\/body&gt;\n&lt;\/html&gt;\n<\/code>\n<\/pre>\n\n\n\n<p>In this example, the <code>\/players<\/code> route queries the database for all players and passes the results to the <code>show_players.html<\/code> template, which displays the players in a list.<\/p>\n\n\n\n<p>By following these steps, you can integrate SQLAlchemy with Flask to build a simple web application that interacts with a TiDB database. These practical SQLAlchemy examples demonstrate how to set up your environment, handle user input, and display data, providing a solid foundation for more complex applications.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity\"\/>\n\n\n\n<p>In this tutorial, we covered essential aspects of SQLAlchemy, from installation and setup to advanced querying techniques and integration with Flask. The practical SQLAlchemy examples provided should give you a solid foundation to start building robust database-driven applications. We encourage you to explore further and experiment with different features of SQLAlchemy to fully leverage its capabilities. For continued learning, consider diving into the official SQLAlchemy documentation and other resources to deepen your understanding and enhance your skills.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Master SQLAlchemy with practical examples for Python developers. Learn installation, ORM, CRUD operations, advanced queries, and Flask integration.<\/p>","protected":false},"author":8,"featured_media":0,"template":"","class_list":["post-18401","article","type-article","status-publish","hentry"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.9 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>SQLAlchemy Tutorial: Practical Examples for Python Coders<\/title>\n<meta name=\"description\" content=\"Master SQLAlchemy with practical examples for Python developers. Learn installation, ORM, CRUD operations, advanced queries, and Flask integration.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.pingcap.com\/ko\/article\/sqlalchemy-tutorial-practical-examples-for-python-coders\/\" \/>\n<meta property=\"og:locale\" content=\"ko_KR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"SQLAlchemy Tutorial: Practical Examples for Python Coders\" \/>\n<meta property=\"og:description\" content=\"Master SQLAlchemy with practical examples for Python developers. Learn installation, ORM, CRUD operations, advanced queries, and Flask integration.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.pingcap.com\/ko\/article\/sqlalchemy-tutorial-practical-examples-for-python-coders\/\" \/>\n<meta property=\"og:site_name\" content=\"TiDB\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/facebook.com\/pingcap2015\" \/>\n<meta property=\"article:modified_time\" content=\"2024-12-12T10:03:50+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/static.pingcap.com\/files\/2024\/09\/11005522\/Homepage-Ad.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1440\" \/>\n\t<meta property=\"og:image:height\" content=\"714\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:site\" content=\"@PingCAP\" \/>\n<meta name=\"twitter:label1\" content=\"\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04\" \/>\n\t<meta name=\"twitter:data1\" content=\"14\ubd84\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.pingcap.com\/article\/sqlalchemy-tutorial-practical-examples-for-python-coders\/\",\"url\":\"https:\/\/www.pingcap.com\/article\/sqlalchemy-tutorial-practical-examples-for-python-coders\/\",\"name\":\"SQLAlchemy Tutorial: Practical Examples for Python Coders\",\"isPartOf\":{\"@id\":\"https:\/\/www.pingcap.com\/#website\"},\"datePublished\":\"2024-07-17T06:56:36+00:00\",\"dateModified\":\"2024-12-12T10:03:50+00:00\",\"description\":\"Master SQLAlchemy with practical examples for Python developers. Learn installation, ORM, CRUD operations, advanced queries, and Flask integration.\",\"breadcrumb\":{\"@id\":\"https:\/\/www.pingcap.com\/article\/sqlalchemy-tutorial-practical-examples-for-python-coders\/#breadcrumb\"},\"inLanguage\":\"ko-KR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.pingcap.com\/article\/sqlalchemy-tutorial-practical-examples-for-python-coders\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.pingcap.com\/article\/sqlalchemy-tutorial-practical-examples-for-python-coders\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.pingcap.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Articles\",\"item\":\"https:\/\/www.pingcap.com\/article\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"SQLAlchemy Tutorial: Practical Examples for Python Coders\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.pingcap.com\/#website\",\"url\":\"https:\/\/www.pingcap.com\/\",\"name\":\"TiDB\",\"description\":\"TiDB | SQL at Scale\",\"publisher\":{\"@id\":\"https:\/\/www.pingcap.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.pingcap.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"ko-KR\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.pingcap.com\/#organization\",\"name\":\"PingCAP\",\"url\":\"https:\/\/www.pingcap.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/www.pingcap.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/static.pingcap.com\/files\/2021\/11\/pingcap-logo.png\",\"contentUrl\":\"https:\/\/static.pingcap.com\/files\/2021\/11\/pingcap-logo.png\",\"width\":811,\"height\":232,\"caption\":\"PingCAP\"},\"image\":{\"@id\":\"https:\/\/www.pingcap.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/facebook.com\/pingcap2015\",\"https:\/\/x.com\/PingCAP\",\"https:\/\/linkedin.com\/company\/pingcap\",\"https:\/\/youtube.com\/channel\/UCuq4puT32DzHKT5rU1IZpIA\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"SQLAlchemy Tutorial: Practical Examples for Python Coders","description":"Master SQLAlchemy with practical examples for Python developers. Learn installation, ORM, CRUD operations, advanced queries, and Flask integration.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.pingcap.com\/ko\/article\/sqlalchemy-tutorial-practical-examples-for-python-coders\/","og_locale":"ko_KR","og_type":"article","og_title":"SQLAlchemy Tutorial: Practical Examples for Python Coders","og_description":"Master SQLAlchemy with practical examples for Python developers. Learn installation, ORM, CRUD operations, advanced queries, and Flask integration.","og_url":"https:\/\/www.pingcap.com\/ko\/article\/sqlalchemy-tutorial-practical-examples-for-python-coders\/","og_site_name":"TiDB","article_publisher":"https:\/\/facebook.com\/pingcap2015","article_modified_time":"2024-12-12T10:03:50+00:00","og_image":[{"width":1440,"height":714,"url":"https:\/\/static.pingcap.com\/files\/2024\/09\/11005522\/Homepage-Ad.png","type":"image\/png"}],"twitter_card":"summary_large_image","twitter_site":"@PingCAP","twitter_misc":{"\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04":"14\ubd84"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.pingcap.com\/article\/sqlalchemy-tutorial-practical-examples-for-python-coders\/","url":"https:\/\/www.pingcap.com\/article\/sqlalchemy-tutorial-practical-examples-for-python-coders\/","name":"SQLAlchemy Tutorial: Practical Examples for Python Coders","isPartOf":{"@id":"https:\/\/www.pingcap.com\/#website"},"datePublished":"2024-07-17T06:56:36+00:00","dateModified":"2024-12-12T10:03:50+00:00","description":"Master SQLAlchemy with practical examples for Python developers. Learn installation, ORM, CRUD operations, advanced queries, and Flask integration.","breadcrumb":{"@id":"https:\/\/www.pingcap.com\/article\/sqlalchemy-tutorial-practical-examples-for-python-coders\/#breadcrumb"},"inLanguage":"ko-KR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.pingcap.com\/article\/sqlalchemy-tutorial-practical-examples-for-python-coders\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.pingcap.com\/article\/sqlalchemy-tutorial-practical-examples-for-python-coders\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.pingcap.com\/"},{"@type":"ListItem","position":2,"name":"Articles","item":"https:\/\/www.pingcap.com\/article\/"},{"@type":"ListItem","position":3,"name":"SQLAlchemy Tutorial: Practical Examples for Python Coders"}]},{"@type":"WebSite","@id":"https:\/\/www.pingcap.com\/#website","url":"https:\/\/www.pingcap.com\/","name":"\ud2f0DB","description":"TiDB | SQL at Scale","publisher":{"@id":"https:\/\/www.pingcap.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.pingcap.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"ko-KR"},{"@type":"Organization","@id":"https:\/\/www.pingcap.com\/#organization","name":"PingCAP","url":"https:\/\/www.pingcap.com\/","logo":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/www.pingcap.com\/#\/schema\/logo\/image\/","url":"https:\/\/static.pingcap.com\/files\/2021\/11\/pingcap-logo.png","contentUrl":"https:\/\/static.pingcap.com\/files\/2021\/11\/pingcap-logo.png","width":811,"height":232,"caption":"PingCAP"},"image":{"@id":"https:\/\/www.pingcap.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/facebook.com\/pingcap2015","https:\/\/x.com\/PingCAP","https:\/\/linkedin.com\/company\/pingcap","https:\/\/youtube.com\/channel\/UCuq4puT32DzHKT5rU1IZpIA"]}]}},"card_markup":"        <a class=\"card-article\" href=\"https:\/\/www.pingcap.com\/ko\/article\/sqlalchemy-tutorial-practical-examples-for-python-coders\/\">            <h3>SQLAlchemy Tutorial: Practical Examples for Python Coders<\/h3>            <p>Master SQLAlchemy with practical examples for Python developers. Learn installation, ORM, CRUD operations, advanced queries, and Flask integration.<\/p>        <\/a>","_links":{"self":[{"href":"https:\/\/www.pingcap.com\/ko\/wp-json\/wp\/v2\/article\/18401","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.pingcap.com\/ko\/wp-json\/wp\/v2\/article"}],"about":[{"href":"https:\/\/www.pingcap.com\/ko\/wp-json\/wp\/v2\/types\/article"}],"author":[{"embeddable":true,"href":"https:\/\/www.pingcap.com\/ko\/wp-json\/wp\/v2\/users\/8"}],"wp:attachment":[{"href":"https:\/\/www.pingcap.com\/ko\/wp-json\/wp\/v2\/media?parent=18401"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}