Python: Cannot format SQL query string












0















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
);









share|improve this question

























  • You arent executing your query, you're executing nothing.

    – Loocid
    Nov 22 '18 at 0:46











  • Your code doesn't show the query being passed to the cursor, can you add the traceback?

    – chris
    Nov 22 '18 at 0:46











  • You should use query parameters instead of trying to glue values into your SQL string.

    – khelwood
    Nov 22 '18 at 0:48











  • As @Loocid said, your execute call is empty. You probably wanted execute(query) instead of just execute().

    – John Gordon
    Nov 22 '18 at 0:52













  • sorry, just fixed that

    – AbtPst
    Nov 22 '18 at 0:54
















0















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
);









share|improve this question

























  • You arent executing your query, you're executing nothing.

    – Loocid
    Nov 22 '18 at 0:46











  • Your code doesn't show the query being passed to the cursor, can you add the traceback?

    – chris
    Nov 22 '18 at 0:46











  • You should use query parameters instead of trying to glue values into your SQL string.

    – khelwood
    Nov 22 '18 at 0:48











  • As @Loocid said, your execute call is empty. You probably wanted execute(query) instead of just execute().

    – John Gordon
    Nov 22 '18 at 0:52













  • sorry, just fixed that

    – AbtPst
    Nov 22 '18 at 0:54














0












0








0








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
);









share|improve this question
















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
);






python mysql string-formatting pymysql






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 '18 at 21:57







AbtPst

















asked Nov 22 '18 at 0:40









AbtPstAbtPst

2,99974393




2,99974393













  • You arent executing your query, you're executing nothing.

    – Loocid
    Nov 22 '18 at 0:46











  • Your code doesn't show the query being passed to the cursor, can you add the traceback?

    – chris
    Nov 22 '18 at 0:46











  • You should use query parameters instead of trying to glue values into your SQL string.

    – khelwood
    Nov 22 '18 at 0:48











  • As @Loocid said, your execute call is empty. You probably wanted execute(query) instead of just execute().

    – John Gordon
    Nov 22 '18 at 0:52













  • sorry, just fixed that

    – AbtPst
    Nov 22 '18 at 0:54



















  • You arent executing your query, you're executing nothing.

    – Loocid
    Nov 22 '18 at 0:46











  • Your code doesn't show the query being passed to the cursor, can you add the traceback?

    – chris
    Nov 22 '18 at 0:46











  • You should use query parameters instead of trying to glue values into your SQL string.

    – khelwood
    Nov 22 '18 at 0:48











  • As @Loocid said, your execute call is empty. You probably wanted execute(query) instead of just execute().

    – John Gordon
    Nov 22 '18 at 0:52













  • sorry, just fixed that

    – AbtPst
    Nov 22 '18 at 0:54

















You arent executing your query, you're executing nothing.

– Loocid
Nov 22 '18 at 0:46





You arent executing your query, you're executing nothing.

– Loocid
Nov 22 '18 at 0:46













Your code doesn't show the query being passed to the cursor, can you add the traceback?

– chris
Nov 22 '18 at 0:46





Your code doesn't show the query being passed to the cursor, can you add the traceback?

– chris
Nov 22 '18 at 0:46













You should use query parameters instead of trying to glue values into your SQL string.

– khelwood
Nov 22 '18 at 0:48





You should use query parameters instead of trying to glue values into your SQL string.

– khelwood
Nov 22 '18 at 0:48













As @Loocid said, your execute call is empty. You probably wanted execute(query) instead of just execute().

– John Gordon
Nov 22 '18 at 0:52







As @Loocid said, your execute call is empty. You probably wanted execute(query) instead of just execute().

– John Gordon
Nov 22 '18 at 0:52















sorry, just fixed that

– AbtPst
Nov 22 '18 at 0:54





sorry, just fixed that

– AbtPst
Nov 22 '18 at 0:54












1 Answer
1






active

oldest

votes


















2














Look at the following example in the MySQL connector-python documentation for insert. Don't use format for your prepared statement parameters, instead pass them as the second argument to execute. The example shows passing the data both as a tuple and a dict:



from __future__ import print_function
from datetime import date, datetime, timedelta
import mysql.connector

cnx = mysql.connector.connect(user='scott', database='employees')
cursor = cnx.cursor()

tomorrow = datetime.now().date() + timedelta(days=1)

add_employee = ("INSERT INTO employees "
"(first_name, last_name, hire_date, gender, birth_date) "
"VALUES (%s, %s, %s, %s, %s)")
add_salary = ("INSERT INTO salaries "
"(emp_no, salary, from_date, to_date) "
"VALUES (%(emp_no)s, %(salary)s, %(from_date)s, %(to_date)s)")

data_employee = ('Geert', 'Vanderkelen', tomorrow, 'M', date(1977, 6, 14))

# Insert new employee
cursor.execute(add_employee, data_employee)
emp_no = cursor.lastrowid

# Insert salary information
data_salary = {
'emp_no': emp_no,
'salary': 50000,
'from_date': tomorrow,
'to_date': date(9999, 1, 1),
}
cursor.execute(add_salary, data_salary)

# Make sure data is committed to the database
cnx.commit()

cursor.close()
cnx.close()


Additionally, you probably need to call commit as the documentation states




Since by default Connector/Python turns autocommit off, and MySQL 5.5
and higher uses transactional InnoDB tables by default, it is
necessary to commit your changes using the connection's commit()
method. You could also roll back using the rollback() method.




Edit:



I'm not sure why you're still having issues with the query being improperly escaped, I've replicated your conditions as closely as possible and it works fine:



Table:



MariaDB [pets]> DESCRIBE myTable;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| col1 | varchar(50) | NO | | NULL | |
| col2 | varchar(100) | NO | | NULL | |
+-------+--------------+------+-----+---------+-------+


Python code:



import mysql.connector

cnx = mysql.connector.connect(user='cody', password='secret', database='pets')
cursor = cnx.cursor()

a = 'val1'
b = 'val2'

query = "insert into myTable values (%s, %s)"

cursor.execute(query, (a,b))

cnx.commit()

print(cursor._executed)

cursor.close()
cnx.close()


The program runs successfully and prints the executed query as expected:



cody@servo:~$ python mysql-test.py
insert into myTable values ('val1', 'val2')


And the row is inserted:



MariaDB [pets]> SELECT * FROM myTable;
+------+------+
| col1 | col2 |
+------+------+
| val1 | val2 |
+------+------+
1 row in set (0.01 sec)





share|improve this answer


























  • thanks a lot cody!

    – AbtPst
    Nov 23 '18 at 20:15













  • please see the latest update. I get a different error now 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

    – AbtPst
    Nov 23 '18 at 20:48








  • 1





    I'm not sure what that could be, the only thing I see that's off is you should be caling commit on the connection object, not the cursor. What is the structure of mytable? Can you include the output of DESCRIBE mytable?

    – cody
    Nov 23 '18 at 21:46













  • thanks cody. i added the information in the post

    – AbtPst
    Nov 23 '18 at 21:57











  • by the way, are you using python 3?

    – AbtPst
    Nov 23 '18 at 22:17











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53422394%2fpython-cannot-format-sql-query-string%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














Look at the following example in the MySQL connector-python documentation for insert. Don't use format for your prepared statement parameters, instead pass them as the second argument to execute. The example shows passing the data both as a tuple and a dict:



from __future__ import print_function
from datetime import date, datetime, timedelta
import mysql.connector

cnx = mysql.connector.connect(user='scott', database='employees')
cursor = cnx.cursor()

tomorrow = datetime.now().date() + timedelta(days=1)

add_employee = ("INSERT INTO employees "
"(first_name, last_name, hire_date, gender, birth_date) "
"VALUES (%s, %s, %s, %s, %s)")
add_salary = ("INSERT INTO salaries "
"(emp_no, salary, from_date, to_date) "
"VALUES (%(emp_no)s, %(salary)s, %(from_date)s, %(to_date)s)")

data_employee = ('Geert', 'Vanderkelen', tomorrow, 'M', date(1977, 6, 14))

# Insert new employee
cursor.execute(add_employee, data_employee)
emp_no = cursor.lastrowid

# Insert salary information
data_salary = {
'emp_no': emp_no,
'salary': 50000,
'from_date': tomorrow,
'to_date': date(9999, 1, 1),
}
cursor.execute(add_salary, data_salary)

# Make sure data is committed to the database
cnx.commit()

cursor.close()
cnx.close()


Additionally, you probably need to call commit as the documentation states




Since by default Connector/Python turns autocommit off, and MySQL 5.5
and higher uses transactional InnoDB tables by default, it is
necessary to commit your changes using the connection's commit()
method. You could also roll back using the rollback() method.




Edit:



I'm not sure why you're still having issues with the query being improperly escaped, I've replicated your conditions as closely as possible and it works fine:



Table:



MariaDB [pets]> DESCRIBE myTable;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| col1 | varchar(50) | NO | | NULL | |
| col2 | varchar(100) | NO | | NULL | |
+-------+--------------+------+-----+---------+-------+


Python code:



import mysql.connector

cnx = mysql.connector.connect(user='cody', password='secret', database='pets')
cursor = cnx.cursor()

a = 'val1'
b = 'val2'

query = "insert into myTable values (%s, %s)"

cursor.execute(query, (a,b))

cnx.commit()

print(cursor._executed)

cursor.close()
cnx.close()


The program runs successfully and prints the executed query as expected:



cody@servo:~$ python mysql-test.py
insert into myTable values ('val1', 'val2')


And the row is inserted:



MariaDB [pets]> SELECT * FROM myTable;
+------+------+
| col1 | col2 |
+------+------+
| val1 | val2 |
+------+------+
1 row in set (0.01 sec)





share|improve this answer


























  • thanks a lot cody!

    – AbtPst
    Nov 23 '18 at 20:15













  • please see the latest update. I get a different error now 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

    – AbtPst
    Nov 23 '18 at 20:48








  • 1





    I'm not sure what that could be, the only thing I see that's off is you should be caling commit on the connection object, not the cursor. What is the structure of mytable? Can you include the output of DESCRIBE mytable?

    – cody
    Nov 23 '18 at 21:46













  • thanks cody. i added the information in the post

    – AbtPst
    Nov 23 '18 at 21:57











  • by the way, are you using python 3?

    – AbtPst
    Nov 23 '18 at 22:17
















2














Look at the following example in the MySQL connector-python documentation for insert. Don't use format for your prepared statement parameters, instead pass them as the second argument to execute. The example shows passing the data both as a tuple and a dict:



from __future__ import print_function
from datetime import date, datetime, timedelta
import mysql.connector

cnx = mysql.connector.connect(user='scott', database='employees')
cursor = cnx.cursor()

tomorrow = datetime.now().date() + timedelta(days=1)

add_employee = ("INSERT INTO employees "
"(first_name, last_name, hire_date, gender, birth_date) "
"VALUES (%s, %s, %s, %s, %s)")
add_salary = ("INSERT INTO salaries "
"(emp_no, salary, from_date, to_date) "
"VALUES (%(emp_no)s, %(salary)s, %(from_date)s, %(to_date)s)")

data_employee = ('Geert', 'Vanderkelen', tomorrow, 'M', date(1977, 6, 14))

# Insert new employee
cursor.execute(add_employee, data_employee)
emp_no = cursor.lastrowid

# Insert salary information
data_salary = {
'emp_no': emp_no,
'salary': 50000,
'from_date': tomorrow,
'to_date': date(9999, 1, 1),
}
cursor.execute(add_salary, data_salary)

# Make sure data is committed to the database
cnx.commit()

cursor.close()
cnx.close()


Additionally, you probably need to call commit as the documentation states




Since by default Connector/Python turns autocommit off, and MySQL 5.5
and higher uses transactional InnoDB tables by default, it is
necessary to commit your changes using the connection's commit()
method. You could also roll back using the rollback() method.




Edit:



I'm not sure why you're still having issues with the query being improperly escaped, I've replicated your conditions as closely as possible and it works fine:



Table:



MariaDB [pets]> DESCRIBE myTable;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| col1 | varchar(50) | NO | | NULL | |
| col2 | varchar(100) | NO | | NULL | |
+-------+--------------+------+-----+---------+-------+


Python code:



import mysql.connector

cnx = mysql.connector.connect(user='cody', password='secret', database='pets')
cursor = cnx.cursor()

a = 'val1'
b = 'val2'

query = "insert into myTable values (%s, %s)"

cursor.execute(query, (a,b))

cnx.commit()

print(cursor._executed)

cursor.close()
cnx.close()


The program runs successfully and prints the executed query as expected:



cody@servo:~$ python mysql-test.py
insert into myTable values ('val1', 'val2')


And the row is inserted:



MariaDB [pets]> SELECT * FROM myTable;
+------+------+
| col1 | col2 |
+------+------+
| val1 | val2 |
+------+------+
1 row in set (0.01 sec)





share|improve this answer


























  • thanks a lot cody!

    – AbtPst
    Nov 23 '18 at 20:15













  • please see the latest update. I get a different error now 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

    – AbtPst
    Nov 23 '18 at 20:48








  • 1





    I'm not sure what that could be, the only thing I see that's off is you should be caling commit on the connection object, not the cursor. What is the structure of mytable? Can you include the output of DESCRIBE mytable?

    – cody
    Nov 23 '18 at 21:46













  • thanks cody. i added the information in the post

    – AbtPst
    Nov 23 '18 at 21:57











  • by the way, are you using python 3?

    – AbtPst
    Nov 23 '18 at 22:17














2












2








2







Look at the following example in the MySQL connector-python documentation for insert. Don't use format for your prepared statement parameters, instead pass them as the second argument to execute. The example shows passing the data both as a tuple and a dict:



from __future__ import print_function
from datetime import date, datetime, timedelta
import mysql.connector

cnx = mysql.connector.connect(user='scott', database='employees')
cursor = cnx.cursor()

tomorrow = datetime.now().date() + timedelta(days=1)

add_employee = ("INSERT INTO employees "
"(first_name, last_name, hire_date, gender, birth_date) "
"VALUES (%s, %s, %s, %s, %s)")
add_salary = ("INSERT INTO salaries "
"(emp_no, salary, from_date, to_date) "
"VALUES (%(emp_no)s, %(salary)s, %(from_date)s, %(to_date)s)")

data_employee = ('Geert', 'Vanderkelen', tomorrow, 'M', date(1977, 6, 14))

# Insert new employee
cursor.execute(add_employee, data_employee)
emp_no = cursor.lastrowid

# Insert salary information
data_salary = {
'emp_no': emp_no,
'salary': 50000,
'from_date': tomorrow,
'to_date': date(9999, 1, 1),
}
cursor.execute(add_salary, data_salary)

# Make sure data is committed to the database
cnx.commit()

cursor.close()
cnx.close()


Additionally, you probably need to call commit as the documentation states




Since by default Connector/Python turns autocommit off, and MySQL 5.5
and higher uses transactional InnoDB tables by default, it is
necessary to commit your changes using the connection's commit()
method. You could also roll back using the rollback() method.




Edit:



I'm not sure why you're still having issues with the query being improperly escaped, I've replicated your conditions as closely as possible and it works fine:



Table:



MariaDB [pets]> DESCRIBE myTable;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| col1 | varchar(50) | NO | | NULL | |
| col2 | varchar(100) | NO | | NULL | |
+-------+--------------+------+-----+---------+-------+


Python code:



import mysql.connector

cnx = mysql.connector.connect(user='cody', password='secret', database='pets')
cursor = cnx.cursor()

a = 'val1'
b = 'val2'

query = "insert into myTable values (%s, %s)"

cursor.execute(query, (a,b))

cnx.commit()

print(cursor._executed)

cursor.close()
cnx.close()


The program runs successfully and prints the executed query as expected:



cody@servo:~$ python mysql-test.py
insert into myTable values ('val1', 'val2')


And the row is inserted:



MariaDB [pets]> SELECT * FROM myTable;
+------+------+
| col1 | col2 |
+------+------+
| val1 | val2 |
+------+------+
1 row in set (0.01 sec)





share|improve this answer















Look at the following example in the MySQL connector-python documentation for insert. Don't use format for your prepared statement parameters, instead pass them as the second argument to execute. The example shows passing the data both as a tuple and a dict:



from __future__ import print_function
from datetime import date, datetime, timedelta
import mysql.connector

cnx = mysql.connector.connect(user='scott', database='employees')
cursor = cnx.cursor()

tomorrow = datetime.now().date() + timedelta(days=1)

add_employee = ("INSERT INTO employees "
"(first_name, last_name, hire_date, gender, birth_date) "
"VALUES (%s, %s, %s, %s, %s)")
add_salary = ("INSERT INTO salaries "
"(emp_no, salary, from_date, to_date) "
"VALUES (%(emp_no)s, %(salary)s, %(from_date)s, %(to_date)s)")

data_employee = ('Geert', 'Vanderkelen', tomorrow, 'M', date(1977, 6, 14))

# Insert new employee
cursor.execute(add_employee, data_employee)
emp_no = cursor.lastrowid

# Insert salary information
data_salary = {
'emp_no': emp_no,
'salary': 50000,
'from_date': tomorrow,
'to_date': date(9999, 1, 1),
}
cursor.execute(add_salary, data_salary)

# Make sure data is committed to the database
cnx.commit()

cursor.close()
cnx.close()


Additionally, you probably need to call commit as the documentation states




Since by default Connector/Python turns autocommit off, and MySQL 5.5
and higher uses transactional InnoDB tables by default, it is
necessary to commit your changes using the connection's commit()
method. You could also roll back using the rollback() method.




Edit:



I'm not sure why you're still having issues with the query being improperly escaped, I've replicated your conditions as closely as possible and it works fine:



Table:



MariaDB [pets]> DESCRIBE myTable;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| col1 | varchar(50) | NO | | NULL | |
| col2 | varchar(100) | NO | | NULL | |
+-------+--------------+------+-----+---------+-------+


Python code:



import mysql.connector

cnx = mysql.connector.connect(user='cody', password='secret', database='pets')
cursor = cnx.cursor()

a = 'val1'
b = 'val2'

query = "insert into myTable values (%s, %s)"

cursor.execute(query, (a,b))

cnx.commit()

print(cursor._executed)

cursor.close()
cnx.close()


The program runs successfully and prints the executed query as expected:



cody@servo:~$ python mysql-test.py
insert into myTable values ('val1', 'val2')


And the row is inserted:



MariaDB [pets]> SELECT * FROM myTable;
+------+------+
| col1 | col2 |
+------+------+
| val1 | val2 |
+------+------+
1 row in set (0.01 sec)






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 23 '18 at 22:16

























answered Nov 22 '18 at 1:17









codycody

3,44121024




3,44121024













  • thanks a lot cody!

    – AbtPst
    Nov 23 '18 at 20:15













  • please see the latest update. I get a different error now 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

    – AbtPst
    Nov 23 '18 at 20:48








  • 1





    I'm not sure what that could be, the only thing I see that's off is you should be caling commit on the connection object, not the cursor. What is the structure of mytable? Can you include the output of DESCRIBE mytable?

    – cody
    Nov 23 '18 at 21:46













  • thanks cody. i added the information in the post

    – AbtPst
    Nov 23 '18 at 21:57











  • by the way, are you using python 3?

    – AbtPst
    Nov 23 '18 at 22:17



















  • thanks a lot cody!

    – AbtPst
    Nov 23 '18 at 20:15













  • please see the latest update. I get a different error now 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

    – AbtPst
    Nov 23 '18 at 20:48








  • 1





    I'm not sure what that could be, the only thing I see that's off is you should be caling commit on the connection object, not the cursor. What is the structure of mytable? Can you include the output of DESCRIBE mytable?

    – cody
    Nov 23 '18 at 21:46













  • thanks cody. i added the information in the post

    – AbtPst
    Nov 23 '18 at 21:57











  • by the way, are you using python 3?

    – AbtPst
    Nov 23 '18 at 22:17

















thanks a lot cody!

– AbtPst
Nov 23 '18 at 20:15







thanks a lot cody!

– AbtPst
Nov 23 '18 at 20:15















please see the latest update. I get a different error now 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

– AbtPst
Nov 23 '18 at 20:48







please see the latest update. I get a different error now 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

– AbtPst
Nov 23 '18 at 20:48






1




1





I'm not sure what that could be, the only thing I see that's off is you should be caling commit on the connection object, not the cursor. What is the structure of mytable? Can you include the output of DESCRIBE mytable?

– cody
Nov 23 '18 at 21:46







I'm not sure what that could be, the only thing I see that's off is you should be caling commit on the connection object, not the cursor. What is the structure of mytable? Can you include the output of DESCRIBE mytable?

– cody
Nov 23 '18 at 21:46















thanks cody. i added the information in the post

– AbtPst
Nov 23 '18 at 21:57





thanks cody. i added the information in the post

– AbtPst
Nov 23 '18 at 21:57













by the way, are you using python 3?

– AbtPst
Nov 23 '18 at 22:17





by the way, are you using python 3?

– AbtPst
Nov 23 '18 at 22:17


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53422394%2fpython-cannot-format-sql-query-string%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Berounka

Sphinx de Gizeh

Different font size/position of beamer's navigation symbols template's content depending on regular/plain...