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)
However, this produces the error:
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'delimiter ';;'\nCREATE PROCEDURE schema_change() BEGIN\n\n if exists (select * f' at line 1")
What could be the problem?
The execute()
method (usually) only executes a single command at a time, so the script cannot be parsed, and anyway there is no support for DELIMITER
; see this comment on GitHub. Therefore, one solution is to have multiple calls:
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;
NOTE: There is a syntax error here, we need to further add:
END IF;
Now continue as before:
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
""")