I am trying use insert query to write to a MariaDB database using Python(3.6).
I am able to successfully connect to the database but insert query with variable doesn't seem to work. But, when I use insert query directly inside .execute() without variable, it seems to work.
script = "insert INTO Table1 (Column1) VALUES (%s)"
val=("911")
mycursor.execute(script,val)
I am getting following programming error for above code:
ProgrammingError: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '%s)' at line 1
Any pointers in right direction would be appreciated.
Either you need to set the paramstyle to 'format'
or you have to use another paramstyle. In MySQL Connector/Python eg the default paramstyle is 'pyformat'
and not 'format'
.
That is the problem
>>> val=("911")
>>> type(val)
<class 'str'>
>>> val
'911'
In Python3, redundant parentheses will be removed so it will interpret it as a string and not a tuple, which is required when working with %s
. You need to use val=('911",)
to force val to be of type tuple
>>> val=("911",)
>>> type(val)
<class 'tuple'>
>>> val
('911',)
script = "insert INTO Table1 (Column1) VALUES ('%s')"
val=("911")
mycursor.execute(script,val)
Try this, I used to have similar issues with sqlite3.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.