mysql.connector, multi=True, sql variable assignment not working

有些话、适合烂在心里 提交于 2019-12-11 03:23:07

问题


SQL code (all in one file that is eventually saved in the python variable "query"):

select @dtmax:=DATE_FORMAT(max(dt), '%Y%m') from table_A;
delete from table_B where  DATE_FORMAT(dt, '%Y%m')=@dtmax;

Does mysql-connector allow the use of variable assignment like I've done in the query above. i.e. take the value of max(date) from TABLE_A and delete everything with that date from TABLE_B.

python code:

    c = conn.cursor(buffered=True)
    c.execute(query, multi=True)
    conn.commit()
    conn.close()

All I know is that the 2nd SQL statement doesnt execute.

I can copy and paste the SQL code into Toad and run it there without any problems but not through mysql.connector library. I would have used pandas but this is legacy script written by someone else and I don't have time to re-write everything.

I kindly appreciate some help.


回答1:


When you use multi=True, then execute() will return a generator. You need to iterate over that generator to actually advance the processing to the next sql statement in your multi-statement query:

c = conn.cursor(buffered=True)
results = c.execute(query, multi=True)
for cur in results:
    print('cursor:', cur)
    if cur.with_rows:
        print('result:', cur.fetchall())
conn.commit()
conn.close()

cur.with_rows will be True if there are results to fetch for the current statement.

This is all describend in the documentation of MySQLCursor.execute()



来源:https://stackoverflow.com/questions/32194638/mysql-connector-multi-true-sql-variable-assignment-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!