python中的mysql错误语法

时间:2017-12-28 03:40:32

标签: python python-3.x mysql5

sql = """
DROP PROCEDURE
IF EXISTS schema_change;

delimiter ';;'
CREATE PROCEDURE schema_change() BEGIN

    if exists (select * from information_schema.columns where table_schema = 
    schema() and table_name = 'selectedairport' and column_name = 'GDP') 
    then
        alter table selectedairport drop column GDP;

    alter table selectedairport add column GDP DOUBLE;

end;;

delimiter ';'


CALL schema_change () ; DROP PROCEDURE
IF EXISTS schema_change ;
"""
cursor6.execute(sql)

然而,这会产生错误:

  

pymysql.err.ProgrammingError:(1064,"您的SQL语法中有错误;请查看与您的MySQL服务器版本对应的手册,以获得正确的语法,以便在' delimiter&#39附近使用;;;' \ n创建程序schema_change()BEGIN \ n \ n如果存在(选择* f'在第1行和第34行;)

可能是什么问题?

1 个答案:

答案 0 :(得分:0)

execute()方法(通常)一次只执行一个命令,因此无法解析脚本,无论如何都不支持DELIMITER;见this comment on GitHub。因此,一种解决方案是进行多次调用:

cursor6.execute("""
DROP PROCEDURE
IF EXISTS schema_change
""")

cursor6.execute("""
CREATE PROCEDURE schema_change() BEGIN

    if exists (select * from information_schema.columns where table_schema = 
    schema() and table_name = 'selectedairport' and column_name = 'GDP') 
    then
        alter table selectedairport drop column GDP;

注意:此处存在语法错误,我们需要进一步添加:

    END IF;

现在继续像以前一样:

    alter table selectedairport add column GDP DOUBLE;

end
""")

cursor6.execute("""
CALL schema_change () 
""")

# Or cursor6.callproc('schema_change')

cursor6.execute("""
DROP PROCEDURE
IF EXISTS schema_change
""")