python连接mysql的简单方法(sqlalchemy)

参考文章:https://blog.csdn.net/qq_36019490/article/details/96883453

1. 首先安装sqlalchemy

pip install sqlalchemy

2. 安装DBAPI

首先我们需要选定一个dialect,简单来说就是你用的是哪种数据库,sqlalchemy支持包括但不仅限于以下类型的数据库:

  • PostgreSQL
  • MySQL
  • SQLite
  • Oracle
  • Microsoft SQL Server

 具体查看官方文档:https://docs.sqlalchemy.org/en/13/dialects/

The dialect is the system SQLAlchemy uses to communicate with various types of DBAPI implementations and databases. The sections that follow contain reference documentation and notes specific to the usage of each backend, as well as notes for the various DBAPIs.

All dialects require that an appropriate DBAPI driver is installed.

sqlalchemy无法直接操作数据库,它需要结合一个DBAPI进行操作 ,DBAPI有很多不同的选择,以mysql为例:

  • mysqlclient (maintained fork of MySQL-Python)

  • PyMySQL

  • MySQL Connector/Python

  • CyMySQL

  • OurSQL

  • Google Cloud SQL

  • PyODBC

  • zxjdbc for Jython

目前常用的是pymysql和mysql-connector,这里选择pymysql,要先进行安装:

pip install pymysql

3. 连接数据库

from sqlalchemy import create_engine
import pymysql

# pymysql格式:mysql+pymysql://:@/[?]
# 其余DBAPI格式见官网:https://docs.sqlalchemy.org/en/13/dialects/mysql.html
engine = create_engine('mysql+pymysql://用户名:密码@ip地址/数据库名称')

sql = 'select * from tb_1'

# 读取生成一个dataframe
df = pd.read_sql(sql,engine)

 

你可能感兴趣的:(python,mysql)