python连接SQLAlchemy
程序员文章站
2024-03-02 19:53:34
...
SQLAlchemy安装
pip install pymysql
pip install SQLAlchemy
连接数据库
from sqlalchemy import create_engine
HOST = "127.0.0.1"
PORT = "3306"
DATABASE = "test_sql"
USERNAME = "root"
PASSWORD = "root"
DB_URI = "mysql+pymysql://{username}:{password}@{host}:{post}/{db}?charset=utf8".format(username=USERNAME, password=PASSWORD, host=HOST, post=PORT, db=DATABASE)
# 创建数据库引擎
engine = create_engine(DB_URI)
# 判断是否连接成功
conn = engine.connect()
result = conn.execute("select 1")
print(result.fetchall())
-
如果出现警告
- 解决办法
安装mysql-connector-python驱动
pip install mysql-connector-python
修改代码
engine = create_engine("mysql+pymysql://root:[email protected]/my_db")
改为:
engine = create_engine("mysql+mysqlconnector://root:[email protected]/my_db")
- 完整代码
from sqlalchemy import create_engine
HOST = "127.0.0.1"
PORT = "3306"
DATABASE = "test_sql"
USERNAME = "root"
PASSWORD = "root"
DB_URI = "mysql+mysqlconnector://{username}:{password}@{host}:{post}/{db}?charset=utf8".format(username=USERNAME, password=PASSWORD, host=HOST, post=PORT, db=DATABASE)
# 创建数据库引擎
engine = create_engine(DB_URI)
# 判断是否连接成功
conn = engine.connect()
result = conn.execute("select 1")
print(result.fetchall())
推荐阅读
-
python连接SQLAlchemy
-
Python:sqlalchemy连接mysql数据库
-
python数据预处理之将类别数据转换为数值的方法
-
python虚拟环境virtualenv的使用教程
-
Python解析json之ValueError: Expecting property name enclosed in double quotes: line
-
Python连接mysql[ORM之sqlalchemy]
-
Python:sqlalchemy连接数据库
-
python使用SMTP发送qq或sina邮件
-
用virtualenv建立多个Python独立虚拟开发环境
-
Python 2.x如何设置命令执行的超时时间实例