【问题标题】:mysql error syntax in pythonpython中的mysql错误语法
【发布时间】:2018-06-08 15:19:10
【问题描述】:
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 ';;' 附近使用的正确语法\nCREATE PROCEDURE schema_change( ) BEGIN\n\n 如果存在(在第 1 行选择 * f')

可能是什么问题?

【问题讨论】:

    标签: python python-3.x mysql5


    【解决方案1】:

    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
    """)
    

    【讨论】:

    • It 错误:pymysql.err.ProgrammingError: (1064,“您的 SQL 语法有错误;请查看与您的 MySQL 服务器版本相对应的手册,以获取在 '' 附近使用的正确语法第 10 行")
    • 顺便说一句,注意您也可以使用cursor6.callproc('schema_change') 调用存储过程,可能比通过 SQL 更有效。
    • 啊哈!我注意到存储过程中存在语法错误 - 您需要一个 END IF 来匹配 IF
    • 谢谢,它有效。但它警告:(1305,'PROCEDURE alldata.schema_change 不存在')结果 = self._query(query)
    • 快速搜索显示this question and answer,这表明您需要GRANT EXECUTE ON PROCEDURE alldata.schema_change TO 'myuser'@'localhost';(或ON FUNCTION )。
    猜你喜欢
    • 1970-01-01
    • 2016-08-05
    • 2012-05-16
    • 1970-01-01
    • 1970-01-01
    • 2016-09-29
    • 2017-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多