Python: Cannot format SQL query string
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
|
show 3 more comments
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
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 wantedexecute(query)
instead of justexecute()
.
– John Gordon
Nov 22 '18 at 0:52
sorry, just fixed that
– AbtPst
Nov 22 '18 at 0:54
|
show 3 more comments
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
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
python mysql string-formatting pymysql
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 wantedexecute(query)
instead of justexecute()
.
– John Gordon
Nov 22 '18 at 0:52
sorry, just fixed that
– AbtPst
Nov 22 '18 at 0:54
|
show 3 more comments
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 wantedexecute(query)
instead of justexecute()
.
– 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
|
show 3 more comments
1 Answer
1
active
oldest
votes
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)
thanks a lot cody!
– AbtPst
Nov 23 '18 at 20:15
please see the latest update. I get a different error now1064 (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 calingcommit
on the connection object, not the cursor. What is the structure ofmytable
? Can you include the output ofDESCRIBE 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
|
show 4 more comments
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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)
thanks a lot cody!
– AbtPst
Nov 23 '18 at 20:15
please see the latest update. I get a different error now1064 (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 calingcommit
on the connection object, not the cursor. What is the structure ofmytable
? Can you include the output ofDESCRIBE 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
|
show 4 more comments
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)
thanks a lot cody!
– AbtPst
Nov 23 '18 at 20:15
please see the latest update. I get a different error now1064 (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 calingcommit
on the connection object, not the cursor. What is the structure ofmytable
? Can you include the output ofDESCRIBE 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
|
show 4 more comments
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)
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)
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 now1064 (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 calingcommit
on the connection object, not the cursor. What is the structure ofmytable
? Can you include the output ofDESCRIBE 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
|
show 4 more comments
thanks a lot cody!
– AbtPst
Nov 23 '18 at 20:15
please see the latest update. I get a different error now1064 (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 calingcommit
on the connection object, not the cursor. What is the structure ofmytable
? Can you include the output ofDESCRIBE 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
|
show 4 more comments
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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 justexecute()
.– John Gordon
Nov 22 '18 at 0:52
sorry, just fixed that
– AbtPst
Nov 22 '18 at 0:54