Pymysql table name from variable - python

I am using Python3 and PyMySQL 0.7.9. Version of Mysql is 5.5.57.
Using this query to fetch data from Mysql works:
cur.execute('SELECT date FROM Tablename1 ORDER BY id DESC LIMIT 1')
I would like to get name of table from variable.
Reading Pymysql docs and this Stackoverflow post lead me to belive that this code should work:
dbtable = Tablename1
query = 'SELECT date FROM %s ORDER BY id DESC LIMIT 1'
cur.execute(query, (dbtable, ))
But this results in 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 ''Tablename1' ORDER BY id DESC LIMIT 1' at line 1")
I also tried using quotes but got different error:
query = 'SELECT `date` FROM `%s` ORDER BY `id` DESC LIMIT 1'
cur.execute(query, (dbtable, ))
Results in:
pymysql.err.ProgrammingError: (1146, "Table 'Databasename.'Tablename1'' doesn't exist")
How should the query be changed to allow variable work?

This works for me. Using python 3.8, mariadb 10.2, pymysql
cur = con.cursor()
cur.execute('SELECT field FROM %s ORDER BY id DESC LIMIT 1' %(dbtable))
result = cur.fetchone()
Replace field and dbtable approriately

Like this :
dbtable = input("Table name: ")
query = "SELECT * FROM %s"%(dbtable)
cur.execute(query)
results = cur.fetchall()
for row in results:
print (row[0], row[1], row[2], row[3])

Related

Dynamic query in django with "|" character in WHERE clause and variable in tablename

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

import sqlite3 with a where var like statement

I have this code :
Title= "somewords"
itemID = somenumbers
import sqlite3
db = sqlite3.connect('C:\\db.sqlite')
cursor = db.cursor()
cursor.execute('SELECT itemID FROM itemAttachments WHERE path LIKE "%?%" ', (Title, ))
cursor.execute('SELECT key FROM items WHERE itemID =? ', (itemID,))
The second statement with the where item=? works but the first one with the like gives me troubles.
I have tried many combinaisons like "+Title+" and {} .format(Title), adding or removing the "%...%" but each time I am getting an error: either sqlite3.ProgrammingError: Incorrect number of bindings supplied or sqlite3.OperationalError: near ",": syntax error.
You have to add the % to the parameter:
cursor.execute('SELECT itemID FROM itemAttachments WHERE path LIKE ?', ('%{}%'.format(Title), ))

mysql is showing error in the syntax

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

DatabaseError: ORA-00911: invalid character

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]) + "'"

How to check with python if a table is empty?

Using python and MySQLdb, how can I check if there are any records in a mysql table (innodb)?
Just select a single row. If you get nothing back, it's empty! (Example from the MySQLdb site)
import MySQLdb
db = MySQLdb.connect(passwd="moonpie", db="thangs")
results = db.query("""SELECT * from mytable limit 1""")
if not results:
print "This table is empty!"
Something like
import MySQLdb
db = MySQLdb.connect("host", "user", "password", "dbname")
cursor = db.cursor()
sql = """SELECT count(*) as tot FROM simpletable"""
cursor.execute(sql)
data = cursor.fetchone()
db.close()
print data
will print the number or records in the simpletable table.
You can then test if to see if it is bigger than zero.

Categories