I have a database created from
CREATE TABLE `ip` (
`idip` int(11) NOT NULL AUTO_INCREMENT,
`ip` decimal(45,0) DEFAULT NULL,
`mask` int(11) DEFAULT NULL,
PRIMARY KEY (`idip`),
UNIQUE KEY `ip_UNIQUE` (`ip`)
)
And I've made some insertions into this table
But when I try to execute on python:
sql = "select idip from ip where ip=%s and mask=%s" % (long(next_hop), 'DEFAULT')
cursor.execute(sql)
idnext_hop = cursor.fetchone()[0]
I get the following error:
Inserting routes into table routes (1/377)...('insere_tabela_routes: Error on insertion at table routes, - SQL: ', 'select idip from ip where ip=0 and mask=DEFAULT')
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
Does anyone have a clue on what is the problem?
mysql.connector uses %s instead of ? as the parameter marker, but you are circumventing it by using Python string formatting. Try this:
sql = "select idip from ip where ip=%s and mask=%s"
cursor.execute(sql, (long(next_hop), 'DEFAULT'))
idnext_hop = cursor.fetchone()[0]
You are munging the query string with parameters, rather than passing them in as, well, parameters. The code should look like this:
sql = "select idip from ip where ip = ? and mask = ?"
cursor.execute(sql, (long(next_hop), 'DEFAULT'))
idnext_hop = cursor.fetchone()[0]
In other words, you want the query engine to do the substitution into the query. You don't want Python to do the substitution into the query string.
Related
I have an existing table in the cloud and I want to make a copy of it. I connect to my database via pymysql, extract the username from an input provided from the new user, and I want to create a new table that will be called by the username, and that table will be a copy of the original one. When I run the code below, I have the following error:
pymysql.err.ProgrammingError: (1064, "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 ''username' AS SELECT * FROM original_table' at line 1")
uname = blabla#bla.com
conn = pymysql.connect(
host="db.host",
port=int(3306),
user=user,
passwd=password,
db=db,
charset='utf8mb4'
)
cur = conn.cursor()
table_name = uname.replace('#', '_').replace('.', '_')
print('TABLE NAME:', table_name)
cur.execute(""" CREATE TABLE %s AS SELECT * FROM original_table """, (table_name))
Parameter quoting is for quoting values. Quoting table names does not work, because in MySQL the way to quote a table name is by using backticks (`), not quotation marks.
MariaDB [test]> CREATE TABLE 'username' AS SELECT * FROM my_table;
ERROR 1064 (42000): 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 ''username' AS SELECT * FROM my_table' at line 1
In this cause you need to use string formatting to create the SQL statement (you can use backticks to defend against SQL-injection*):
cur.execute(""" CREATE TABLE `%s` AS SELECT * FROM original_table """ % table_name)
* I'm not an expert on SQL-injection, so do some research if table_name originates outside your application.
I am trying to insert basic data into my MySQL table without any success yet I'm using basic tutorials as demos.
mysql.connector.errors.ProgrammingError: 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 '%s)' at line 1
My MySQL
CREATE TABLE awesome (
id int NOT NULL AUTO_INCREMENT,
test varchar(50),
PRIMARY KEY (id)
);
My Python code
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="pass",
database="db"
)
mycursor = mydb.cursor()
sql = "INSERT INTO awesome (test) VALUES (%s)"
val = ("Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
Yes the problem arises when there is only 1 argument in val tuple. Use
val=("Highway 21",)
Note the comma at the end.
I am attempting to update a single value in a single cell in a SQL table using the mysql connector for python. Using the following code, I get no error messages, but nor does the table actually update. The value of the cell that I am attempting to update is sometimes empty, sometimes NULL, and sometimes contains a string. Here is my code:
query = ("UPDATE data_set SET %s = '%s' WHERE id = %s") % (column_to_change, change_to_value, row_id)
What am I doing wrong?
Edit: Thanks for the replies so far. I do not think there is any functional issue with the surrounding code (outside of the vulnerability to SQL injection, which I have fixed, here and elsewhere), as I have been effective executing similar code with different queries. Here is my code now:
column_to_change = "column2"
change_to_value = "james"
id = "1234"
cnx = mysql.connector.connect(user='user', password='password',
host='db.website.com',
database='database')
cursor = cnx.cursor()
query = ("UPDATE data_set SET %s = %s WHERE policy_key = %s")
cursor.execute(query, (column_to_change, change_to_value, id))
cursor.close()
cnx.close()
If it's relevant, it turns out the cells I'm trying to insert into are formatted as VARCHAR(45). When I run a SELECT query on a cell, it returns a name formatted like: (u'James',)
If I set change_to_value = "(u'James',)", I receive the following error message:
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntac; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''column1' = '(u\'James\',)' WHERE id = '1234'' at line 1
Make sure you are following all the steps:
conn = pyodbc.connect("SERVER=my.server;DATABASE=my_database;UID=my_user;PWD=my_password;",ansi=True)
cursor = conn.cursor()
query = ("UPDATE data_set SET %s = '%s' WHERE id = %s") % (column_to_change, change_to_value, row_id)
cursor.execute(query)
And also verify the SQL query that your passing to .execute() is same as that you want to run on your database
Depending on your version of Python, perhaps it is an issue with your string interpolation. Otherwise, you may not be connecting your cursor and executing the query successfully. I am assuming you are executing your query elsewhere in your code, but in the instance you are not, this should work:
cursor.execute ("""
UPDATE data_set
SET %s=%s
WHERE id=%s
""", (column_to_change, change_to_value, row_id))
Alternatively, you could store this query in a variable as you have done, assign the respective variables and execute afterward like so:
query = (“UPDATE data_set SET %s=%s WHERE id=%s”)
column_to_change = [YOUR ASSIGNMENT HERE]
change_to_value = [YOUR ASSIGNMENT HERE--if this is a string, it should be formatted as such here]
row_id = [YOUR ASSIGNMENT HERE]
cursor.execute(query, (column_to_change, change_to_value, row_id))
Basic string interpolation is prone to SQL injection and should be avoided.
For more reference, see here
I'm having trouble passing data into %s token. I've looked around and noticed that this Mysql module handles the %s token differently, and that it should be escaped for security reasons, my code is throwing this error.
mysql.connector.errors.ProgrammingError: 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 '%s)' at line 1
If I do it like this:
sql_insert = ("INSERT INTO `Products` (title) VALUES(%s)"),(data)
I get a tuple error..
import mysql.connector
from mysql.connector import errorcode
cnx = mysql.connector.connect (user='userDB1', password='UserPwd1',
host='somedatabase.com', database='mydatabase1')
cursor = cnx.cursor()
sql_insert = ("INSERT INTO `Products` (title) VALUES(%s)")
data=('HelloSQLWORLD')
cursor.execute(sql_insert,data)
cnx.commit()
cnx.close()
No, don't do it the way #Jeon suggested - by using string formatting you are exposing your code to SQL injection attacks. Instead, properly parameterize the query:
query = """
INSERT INTO
Products
(title)
VALUES
(%s)"""
cursor.execute(query, ('HelloSQLWORLD', ))
Note how the query parameters are put into a tuple.
Pythonic string formatting is:
str1 = 'hello'
str2 = 'world'
'%s, %s' % (str1, str2)
Use % with tuple, not ,
For your particular case, try:
cursor.execute(sql_insert % (data))
I have what would appear to be a straight forward insert statement for Oracle SQL. It works properly in Oracle SQL Developer but the same command will not work in Python, complaining about
cx_Oracle.DatabaseError: ORA-00933: SQL command not properly ended.
This happens on the line for the cursor.execute() call. The query itself is:
insert into TestNamesTable (TestName, TheUser, TheProject) values ('mytest.s', 'bjurasz', 'Beta');
If run in SQL Developer I get a new row. Inside Python I get the termination error. From what I can tell its properly formed and terminated.
Here is how I construct the query in python:
sql = "insert into TestNamesTable (TestName, TheUser, TheProject) values ('%s', '%s', '%s');" % (diagname, username, project)
print sql
cursor.execute(sql)
connection.commit()
Try this:
# These are just random definitions, must be of type table requires
diagname = "DEFINE HERE"
username = "SOMEBODY"
project = "PROJECT NAME"
# Assuming you've defined your connection before
cursor.execute("""insert into TestNamesTable (TestName, TheUser, TheProject) values (:diagname, :username, :project)""",
{"diagname": diagname, #cx_Oracle likes this bind-variable looking syntax
"username": username.
"project": project})
connection.commit()