我有dict列表中的数据,我试图将数据插入我的数据库然后我得到错误 sqlalchemy.exc.CompileError:具有当前数据库版本设置的'默认'方言不支持就地多行插入。
from sqlalchemy import create_engine,Table,Column,String,Integer,MetaData,ForeignKey
from sqlalchemy_utils import database_exists,create_database,drop_database
from sqlalchemy.orm import join
engine = create_engine("mysql+mysqldb://root:268454@localhost:3306/sqlalchemy")
conn = engine.connect()
if database_exists(engine.url):
drop_database(engine.url)
create_database(engine.url)
metaData = MetaData()
userTable = Table("user", metaData
, Column("Id", Integer, primary_key = True)
, Column("Name", String(25)))
orderTable = Table("order", metaData
, Column("Id", Integer, primary_key = True)
, Column("UserId", Integer, ForeignKey("user.Id"))
, Column("Desc", String(250)))
try:
metaData.create_all(engine)
except Exception as ex:
print(ex)
users = [
{"Id": 1,
"Name": "user1"},
{"Id": 2,
"Name": "user2"},
{"Id": 3,
"Name": "user3"},
{"Id": 4,
"Name": "user4"}
]
orders = [
{"Id": 1,
"UserId": 1,
"Desc": "desc1"},
{"Id": 2,
"UserId": 1,
"Desc": "desc2"},
{"Id": 3,
"UserId": 2,
"Desc": "desc3"},
{"Id": 4,
"UserId": 2,
"Desc": "desc4"},
]
sql = userTable.insert().values(users)
print(sql) #this line causes the exception
conn.execute(sql)
sql = orderTable.insert().values(orders)
print(sql)
conn.execute(sql)
sql = userTable.select()
print(sql)
returnUsers = conn.execute(sql)
print(returnUsers)
sql = orderTable.select()
print(sql)
returnOrders = conn.execute(sql)
print(returnOrders)
conn.close()
更新:没有print(sql)它可以完美运行。
答案 0 :(得分:2)
如果迭代dicts列表并单独传递dicts,请尝试它是否有效。您尝试做的是使用特殊语法,并非所有方言都可用。
for user in users:
sql = userTable.insert().values(user)
print(sql) #this line causes the exception
conn.execute(sql)
不可否认,sqlalchemy documentation表示MySQL后端应该支持这一点。就个人而言,我不会依赖于不可移植或非标准的东西,并坚持每行一次插入调用,或明确的bulk_insert
方法。
编辑关于打印声明
正如我在评论中提到的,对查询表示的方法打印调用不是方言感知。 但是,您可以检索查询的方言版本,如下所示:
from sqlalchemy.dialects import mysql
print str(q.statement.compile(dialect=mysql.dialect()))
信用到期的信用:Blog post