I want to create a SQL query string and execute it from python
import mysql.connector
from mysql.connector import Error
client = mysql.connector.connect(host=sql_host,
port=sql_port,
database=sql_db,
user=os.environ['SQLUSER'],
passwd=os.environ['SQLPASS']
)
try:
a = "val1"
b = "val2"
cursor = client.cursor()
query = "insert into mytable values ('{}', '{}')".format(a,b)
print(query)
cursor.execute(query)
except Error as e:
print(e)
This does not give me error but at the same time, nothing gets inserted in the table. I think thats because the query string that is created, looks like
"insert into mytable values (\\'val1\\', \\'val2\\')"
I have even tried .replace('\\','') but I cannot get the \\s removed from my query string.
What am I doing wrong?
UPDATE:
Thanks @cody for your help. But now, I am getting a different error
a = 'val1'
b = 'val2'
query = "insert into mytable values (%s, %s)"
print(query)
cursor.execute(query, (a,b))
client.commit()
Now i get
1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
what does this mean? I dont even have any '' in my values
EDIT
While investigating, I see that the _executed attribute of the cursor looks like this
'insert into dev_test_storage values (\\'val1\\', \\'val2\\')'
why do i still have \\ in the query which gets executed?
Here is the create table statement
CREATE TABLE IF NOT EXISTS myTable
(
col1 varchar(50) not null,
col2 varchar (100) not null
);
execute(query)instead of justexecute().