Can't get MySQL source query to work using Python mysqldb module

前端 未结 5 1953
情深已故
情深已故 2021-01-02 20:20

I have the following lines of code:

sql = \"source C:\\\\My Dropbox\\\\workspace\\\\projects\\\\hosted_inv\\\\create_site_db.sql\"
cursor.execute (sql)
         


        
5条回答
  •  情书的邮戳
    2021-01-02 20:40

    I ran into the same problem!

    As a solution I installed the library sqlparse and used the sqlparse.split( sql ) results. I had to check that sql_parts don't include blank lines as solo statements... Otherwise "WOW" sqlparse is pretty great and exactly what I needed!

    import sqlparse 
    ....
    sql = open("test.sql").read()
    sql_parts = sqlparse.split( sql )
    for sql_part in sql_parts:
        if sql_part.strip() ==  '':
            continue 
        cursor.execute( sql_part )
    

    FYI: If you do not run each statement on its own you may get the error "Commands out of sync; you can't run this command now". I only got this error after I added some more queries to my sql file - not the first time around.

提交回复
热议问题