The difference between Python using pymysql and sqlalchemy to access MySQL

The difference between Python using pymysql and sqlalchemy to access MySQL

1. Comparison of two database connection tools

pymysql and sqlalchemy are two libraries in Python that are frequently used to interact with MySQL databases. Both can connect to MySQL databases, but they have obvious differences.

(1) Features

pymysql is a Python module that can be used as a standalone Python file or as a module within a Python program. After installing pymysql, you need to import it and connect to a MySQL database to start interacting with it.
sqlalchemy is a Python library and an ORM (Object Relational Mapper). Through SQLAlchemy, Python objects can be mapped into MySQL database tables. This approach can make MySQL interaction with Python code more intuitive and simpler.
Advantages of SQLAlchemy:
reduce the use of SQL statements, making the code and model more intuitive and clear;
small performance loss; flexible design; strong portability;

(2) Difference

pymysql is suitable enough for connecting to a MySQL database and executing basic SQL queries and commands, while sqlalchemy provides much more functionality.

sqlalchemy includes the ORM, which is responsible for data conversion and type handling. The sqlalchemy ORM uses Python classes to represent database tables, which makes querying and data processing incredibly easy. In addition, sqlalchemy also supports advanced queries and SQL statement generation, which can be more convenient when processing complex queries.

2.Access method

(1)pymysql

import pymysql
 
host = "127.0.0.1:3306"
user = "root"
password = "root"
database = "test"
mysql_db = pymysql.connect(host=host,
                                user=user,
                                password=password,
                                database=database,
                                charset="utf8")
mysql_cursor = mysql_db.cursor()
mysql_cursor.execute('select * from mytable')
cur_rows = mysql_cursor.fetchall()
mysql_cursor.close()

(2)sqlalchemy

from sqlalchemy import create_engine
 
host = "127.0.0.1:3306"
user = "root"
password = "root"
database = "test"
 
mysql_engine = create_engine("mysql+pymysql://{user}:{password}@{host}/{database}")
result = mysql_engine.execute('select * from mytable')

# 输出查询结果
for row in result:
    print(row)

3.Python object mapping SQLAlchemy

Dataframe objects can be saved directly to a MySQL database through SQLAlchemy.

import numpy as np
import pandas as pd

df = pd.DataFrame(np.arange(20).reshape(5,4),
                  columns=['a','b','c','d'],
                  index=[1,2,3,4,5])
df.index.name = 'idx'

df.to_sql(
    'test_drop',  # 定义MySQL表名
    mysql_engine ,
    index=True,  # df 是否包括索引列
    if_exists='append',  # 追加数据模式
    chunksize=20000)  # 批量20000条

Directly save the dataframe to the MySQL database, and the index and table structure are all field-built.

idx	bigint(20)	YES	MUL		
a	bigint(20)	YES			
b	bigint(20)	YES			
c	bigint(20)	YES			
d	bigint(20)	YES			

More SQLAlchemy ORM operations

Guess you like

Origin blog.csdn.net/qq_39065491/article/details/132360712