skip to Main Content

I’m trying to open a SQL template in Python which creates a database with tables and excutes using pymsql. However, I keep getting an error.

import pymysql
import Settings

with open('Settings/databasetemplate.sql', 'r') as sql_file:
    sql = sql_file.read()
conn = pymysql.connect(host='*****', user='*****', password='*****')
cur = conn.cursor()
print(sql)
cur.execute(sql.split(';'))
conn.commit()

The error I keep getting is:

> Traceback (most recent call last):   File
> "D:ProjectsJupiterTest.py", line 9, in <module>
>     cur.execute(sql.split(';'))   File "D:ProjectsJupiterEnviromentlibsite-packagespymysqlcursors.py",
> line 158, in execute
>     result = self._query(query)   File "D:ProjectsJupiterEnviromentlibsite-packagespymysqlcursors.py",
> line 325, in _query
>     conn.query(q)   File "D:ProjectsJupiterEnviromentlibsite-packagespymysqlconnections.py",
> line 548, in query
>     self._execute_command(COMMAND.COM_QUERY, sql)   File "D:ProjectsJupiterEnviromentlibsite-packagespymysqlconnections.py",
> line 817, in _execute_command
>     packet = prelude + sql[: packet_size - 1] TypeError: can't concat list to bytes
> 
> Process finished with exit code 1

2

Answers


  1. Chosen as BEST ANSWER

    I figured it out, as there was multiple lines to query from the SQL. It was only doing the whole file and not line by line. Therefore, with pymysql I changed my code to:

    import pymysql
    import Settings
    from pymysql.constants import CLIENT
    
    conn = pymysql.connect(host='***', user='***', password='***', client_flag=CLIENT.MULTI_STATEMENTS)
    with open('Settings/databasetemplate.sql', 'r') as f:
         with conn.cursor() as cursor:
             cursor.execute(f.read())
         conn.commit()
    

  2. You don’t need to split the commands by the semicolon, but if there’s a reason you need to, you can run the commands individually:

    for command in sql.split(';'):
        cur.execute(command)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search