I am having trouble in executing this query in python. I have an IP database which has 3 column startip, endip and country. Now I want to the location of the ip. this is my code
def get_country(ip):
try:
conn = MySQLConnection(host='localhost', database='ipdb', user ='root', password='password')
cursor = conn.cursor()
query = 'SELECT * FROM db6 WHERE %s BETWEEN INET_ATON(startip) AND INET_ATON(endip)'
ip_inint= ip2int(ip)
cursor.execute(query,ip_inint)
row = cursor.fetchone()
while row is not None:
print " Start range %s end range %s country %s " %(row[0], row[1], row[2])
row = cursor.fetchone()
except Error as error:
print(error)
ip2int function is
def ip2int(addr):
return struct.unpack("!I", socket.inet_aton(addr))[0]
error i am receiving is
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 BETWEEN INET_ATON(startip) AND INET_ATON(endip)' at line 1
what could be the issue?
You need to pass a tuple to execute():
cursor.execute(query, (ip_inint,))
A list will probably work too:
cursor.execute(query, [ip_inint])
An alternative is to use a dictionary with named variables in the query:
query = 'SELECT * FROM db6 WHERE %(ip_inint)s BETWEEN INET_ATON(startip) AND INET_ATON(endip)'
cursor.execute(query, {'ip_inint': ip_inint})
Reference: http://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html
Related
I want to send my variable to MySQL database. But I have a warning. This code was successful to upload.
import mysql.connector
try:
connection = mysql.connector.connect(host='localhost',
database='mydb',
user='root',
password='')
cursor = connection.cursor()
username = 1111111 #example
isian = "tryfile.pkl" #example, i want send string data
print("Before updating a record ")
sql_select_query = """select * from signature where id = %s"""
cursor.execute(sql_select_query %(username))
record = cursor.fetchone()
print(record)
# Update single record now
sql_update_query = """Update signature set signature = "%s" where id = %s"""
cursor.execute(sql_update_query %(isian,username))
connection.commit()
print("Record Updated successfully ")
print("After updating record ")
cursor.execute(sql_select_query)
record = cursor.fetchone()
print(record)
except mysql.connector.Error as error:
print("Failed to update table record: {}".format(error))
finally:
if connection.is_connected():
connection.close()
print("MySQL connection is closed")
Warning
Failed to update table record: 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 '%s' at line 1
I don't understand with error, because I am using MySQL not MariaDB
What's happen to my code?
MariaDB is the engine used in modern MySQL databases.
The problem is your second call to sql_select_query, because you forgot to add the % (username), so nothing was substituted. HOWEVER, you should not be doing the substitutions yourself. You need to let the database connector do it. It's an easy change:
print("Before updating a record ")
sql_select_query = """select * from signature where id = ?"""
cursor.execute(sql_select_query, (username,))
record = cursor.fetchone()
print(record)
# Update single record now
sql_update_query = """Update signature set signature = ? where id = ?"""
cursor.execute(sql_update_query, (isian,username))
connection.commit()
print("Record Updated successfully ")
print("After updating record ")
cursor.execute(sql_select_query, (username,))
record = cursor.fetchone()
print(record)
I want to query MySQL tables using python program but I got this error:
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 ''10' OFFSET '0'' at line 1
The confusing thing is that when I don't use variables, the query runs perfectly as it is shown below:
cur = connection.cursor()
query = "SELECT * FROM DB.Table LIMIT 10 OFFSET 0"
cur.execute(query)
records = cur.fetchall()
for record in records:
print(record)
But I need to select data batch by batch and I have to do the above command in a for loop. And I need to define variables. But I got error 1064. Here is the code with error:
i = 0
p = str(i)
j = 10
q = str(j)
cur = connection.cursor()
query = "SELECT * FROM DB.Table LIMIT %s OFFSET %s"
cur.execute(query,(q,p,))
records = cur.fetchall()
for record in records:
print(record)
I appreciate your help.
Simply, do not convert parameterized values to string as error shows single quotes:
i = 0
j = 10
cur = connection.cursor()
query = "SELECT * FROM DB.Table LIMIT %s OFFSET %s"
cur.execute(query, (j, i))
You can use cur.execute(query % (q,p)) or
query = "SELECT * FROM DB.Table LIMIT {} OFFSET {}"
cur.execute(query.format(q, p))
I have a dynamic sql query running in my views.py and have already ran others that work fine. I am not worried about sql injections because this is a private website. However, the parameters in my And clause has the character "|" in it which throws the error:
Unknown column "X" in 'where clause'
I have looked at solutions but they all use non dynamic query which then prohibits me from making the tablename a variable.
Here is what I want:
mycursor = mydb.cursor()
assembly_name = "peptides_proteins_000005"
group_id = 5
protein_id = "sp|P48740|MASP1_HUMAN"
qry = "SELECT * FROM %s WHERE group_id = %i AND protein_id = %s" % (assembly_name, group_id, protein_id)
mycursor.execute(qry)
But this throws the error:
mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column 'sp' in 'where clause'
When I try doing following the answers of similar questions I get this:
qry = "SELECT * FROM %s WHERE group_id = %i AND protein_id = %s"
mycursor.exectue(qry, (assembly_name, group_id, protein_id))
However, I still get this error:
mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement
Changing the %i to a %s fixes the error above but then I get a new 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 ''peptides_proteins_000005' WHERE group_id = 5 AND protein_id = 'sp|P48740|MASP1_' at line 1
And here is where the loop ends, because looking up this error online suggests to write something similar to the query at the top. Can anybody help me figure out a way to do this?
For me, there was not way to do this, so I had to put literal quotes around the %s.
My final code looked something like this:
assembly_name = peptide_protein_formatter(assembly_name)
mycursor = mydb.cursor()
qry = "SELECT peptide_id,search_id FROM %s WHERE group_id = %s AND protein_id = '%s'" % (assembly_name, group_id, protein_id)
mycursor.execute(qry)
result = mycursor.fetchall()
In the code below, I am trying to insert a boolean value in Network table, where the status field is declared as boolean.
import urllib2
import mysql.connector as conn
import MySQLdb
import logging
class getData:
#staticmethod
def checkNetwork():
try:
urllib2.urlopen('https://www.google.com', timeout = 2)
return True
except urllib2.URLError as err:
return False
#staticmethod
def connectDB():
db = conn.connect(host='****', user='****', passwd='****', db='*******')
cursor = db.cursor()
return db,cursor
#staticmethod
def insertNData(data):
print type(data)
db,cursor = getData.connectDB()
sql_Query = "INSERT INTO Network(status) VALUES(%s);"
try:
result= cursor.execute(sql_Query,data)
db.commit()
logging.warn("%s", result)
logging.info("Success")
except MySQLdb.IntegrityError:
logging.warn("Failed")
finally:
db.close()
return True
netStat = getData.checkNetwork()
getData.insertNData(netStat)
When I run the code, I get the below error
ERROR 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
I tried searching on google to find some solution and also changed a few things to test but still the same error.
Thanks in advance.
There is error in this line:
sql_Query = "INSERT INTO Network(status) VALUES(%s);"
You are not passing the value correctly. You created a placeholder but did not fill it.
Use:
for python3.6 and above:
sql_Query = f"INSERT INTO Network(status) VALUES({data});"
for python 2 and 3:
sql_Query = "INSERT INTO Network(status) VALUES({});".format(data)
or
sql_Query = "INSERT INTO Network(status) VALUES(%s);" %(data)
I have following code to execute sql quesry in Oracle db:
try:
conn = cx_Oracle.connect(DB_LOGIN+"/"+DB_PWD+"#"+SID)
cursor = connection.cursor()
cursor.execute(sql)
connection.commit()
cursor.close()
conn.close()
except cx_Oracle.DatabaseError, ex:
error, = ex.args
print 'Error.code =', error.code
print 'Error.message =' , error.message
print 'Error.offset =', error.offset
conn.rollback()
I got error: DatabaseError: <cx_Orac...40066758>.
Why I don't see full error message in console? Looks like exception part is not executed.
I use python 2.5 and oracle 10.2.0 on linux.
Update: After some investigation I found out that the error is DatabaseError: ORA-00911: invalid character.
My sql string is like: sql = "SELECT ID FROM TABLE WHERE DESC = '" + str(desc[0]) + "';". This is generated string: "SELECT ID FROM TABLE WHERE DESC = '3312';"
When I execute the same request in SQL Developer it works. So what I do wrong?
Delete the semicolon:
sql = "SELECT ID FROM TABLE WHERE DESC = '" + str(desc[0]) + "'"