Is there a way to execute more than one query per string in MySQL-Python?

后端 未结 2 1221
梦谈多话
梦谈多话 2021-01-15 21:27

I have some input which is a string containing more than one MySQL queries, such as USE some_db; SELECT * FROM some_table;. When I store this string as s<

2条回答
  •  有刺的猬
    2021-01-15 22:04

    Certainly, a Python script can run multiple SQL statements from a string or list, external .sql or .txt file that can be sourced to MySQL.

    However, the cur.execute command runs one SQL line one at a time. Hence, you will need to loop through each SQL line iteratively. So, consider splitting the multiple SQL commands by semicolon.

    s = "USE some_db; SELECT * FROM some_table;"
    
    # filter() removes trailing empty list item
    s = filter(None, s.split(';'))
    
    for i in s:
        # strip() removes leading and trailing white spaces  
        # semicolon is re-added per line for query run
        cur.execute(i.strip() + ';')
    

    But be sure to remove any semicolons found in comments.

    # PROCESSING STEP 1;
    # PROCESSING STEP 1
    

提交回复
热议问题