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
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:
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: