问题:
from sqlalchemy import create_engine
# 数据库的变量
HOST = '127.0.0.1'
PORT = 3306
DATA_BASE = 'itbz'
USER='root'
PWD='123456'
# DB_URL = f'数据库的名+驱动名://{USER}:{PWD}@{HOST}:{PORT}/{DATA_BASE}'
DB_URL = f'mysql+pymysql://{USER}:{PWD}@{HOST}:{PORT}/{DATA_BASE}'
engine = create_engine(DB_URL)
# 执行一个SQL
sql ='select 1;'
conn = engine.connect()
rs = conn.execute(sql)
print(rs.fetchone())
执行结果:
解决问题:
在conn.execute()方法处抛出了错误,'select 1'不是一个可执行的对象
文本sql的执行,需要使用sqlalchemy中的text()方法处理字符串,再执行语句
1、导入 from sqlalchemy import text
2、关键部分修改如下:
result = conn.execute(text("select 1"))
from sqlalchemy import create_engine
from sqlalchemy import text
# 数据库的变量
HOST = '127.0.0.1'
PORT = 3306
DATA_BASE = 'itbz'
USER='root'
PWD='123456'
# DB_URL = f'数据库的名+驱动名://{USER}:{PWD}@{HOST}:{PORT}/{DATA_BASE}'
DB_URL = f'mysql+pymysql://{USER}:{PWD}@{HOST}:{PORT}/{DATA_BASE}'
engine = create_engine(DB_URL)
# 执行一个SQL
sql ='select 1;'
conn = engine.connect()
rs = conn.execute(text(sql))
print(rs.fetchone())
执行结果: