import sqlite3 with a where var like statement - python

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

Related

Psycopg2 query remove \n from args

Im using python3 and postgres 11.5.
This is the script :
a = cursor.execute("SELECT tablename FROM pg_catalog.pg_tables limit 5")
for table in a:
cursor.execute("SELECT * FROM pg_prewarm(public.%s)", [table[0]])
a query gets some table names , and the loop query should run table name as the %s.
but for some reason i get the arg table[0] with // /n in the query and its messing it up.
if i print a results i get table names as tuple:
[('sa1591354519',), ('sa1591397719',), ('sa1591397719',)]
so [table[0]] is a string.
the error i get:
1574683839 [16177], ERR, execute ({'Error while connecting to PostgreSQL': SyntaxError('syntax error at or near "\'sa1591440919\'"\nLINE 1: SELECT * FROM pg_prewarm(public.\'sa1591440919\')\n ^\n')},)
what can i do ?
The errors don't have anything to do with the newlines you see, which are just an artifact of the error message. If you were to print out the error, would see:
syntax error at or near "'sa1591440919'"
LINE 1: SELECT * FROM pg_prewarm(public.'sa1591440919')
^
In other words, Postgres doesn't like the table name you're passing because it contains quotes. This is happening because you're trying to treat the table names like a normal query parameter, which causes psycopg to quote them...but that's not what you want in this case.
Just replace your use of query templating with normal Python string substitution:
a = cursor.execute("SELECT tablename FROM pg_catalog.pg_tables limit 5")
for table in a:
cursor.execute("SELECT * FROM pg_prewarm(public.%s)" % (table[0]))
But this won't actually work, because cursor.execute doesn't return a value, so a will be None. You would need to do something like:
cursor.execute("SELECT tablename FROM pg_catalog.pg_tables limit 5")
a = cursor.fetchall()
for table in a:
...

Pymysql table name from variable

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

Execute SQL for different where clause from Python

I am trying to print SQL result through python code, where I an trying to pass different predicates of the where clause from a for loop. But the code only taking the last value from the loop and giving the result.
In the below example I have two distinct id values 'aaa' and 'bbb'. There are 4 records for id value = 'aaa' and 2 records for the id value = 'bbb'.
But the below code only giving me the result for the id value ='bbb' not for id value 'aaa'
Can anyone help to identify what exactly wrong I am doing?
import pymysql
db = pymysql.connect(host="localhost", user="user1", passwd="pass1", db="db1")
cur = db.cursor()
in_lst=['aaa', 'bbb']
for i in in_lst:
Sql = "SELECT id, val, typ FROM test123 Where id='{inpt}'".format(inpt=i)
print(Sql)
cur.execute(Sql)
records = cur.fetchall()
print(records)
db.close()
The result I am getting as below
C:\Python34\python.exe C:/Users/Koushik/PycharmProjects/Test20161204/20170405.py
SELECT id, val, typ FROM test123 Where id='bbb'
(('bbb', 5, '1a'), ('bbb', 17, '1d'))
Process finished with exit code 0
import pymysql
db = pymysql.connect(host="localhost", user="root", passwd="1234", db="sakila")
cur = db.cursor()
in_lst=['1', '2']
for i in in_lst:
Sql = "SELECT * FROM actor Where actor_id='{inpt}'".format(inpt=i)
print(Sql)
cur.execute(Sql)
records = cur.fetchall()
print(records)
db.close()
Indentation is your problem, please update the code according to your needs...
Within your for loop, you're formatting the sql statement to replace "{inpt}" with "aaa". However, before you do anything with that value, you're immediately overwriting it with the "bbb" version.
You would need to either:
Store the results somehow before the next iteration of the loop, then process them outside of the loop.
Process the results within the loop.
Something like the following will give you a list containing both results from the fetchall() calls:
import pymysql
db = pymysql.connect(host="localhost", user="user1", passwd="pass1", db="db1")
cur = db.cursor()
in_lst=['aaa', 'bbb']
records = list()
for i in in_lst:
Sql = "SELECT id, val, typ FROM test123 Where id='{inpt}'".format(inpt=i)
print(Sql)
cur.execute(Sql)
records.append(cur.fetchall())
print(records)
db.close()

How do you read individual values from the same row in a database with sqlite?

I am attempting to read 2 values from the same row in a database but I am only good enough to read the entire line at once. I have added all the code that I think will be relevant:
def find(search, term):
# Helper function for the find function.
with connect("GTINb.db") as db:
cursor = db.cursor()
sql = "select * from GTINb where {} = ?".format(search)
cursor.execute(sql,(term,))
db.commit()
results = cursor.fetchall()
new = str(term)
if results:
results = str(results)
temp = open('temp.txt', 'a')
temp.write(results)
temp.write('\n')
temp.close()
with connect("GTINb.db") as db:
cursor.execute("UPDATE GTINb SET stockcur=stockcur-1 WHERE GTIN8=(?)",(new,))
cur = cursor.execute("SELECT stockcur from GTINb by (?)",(new,))
re = cursor.execute("SELECT restock from GTINb by (?)",(new,))
if cur < re:
cursor.execute("UPDATE GTINb SET stockcur=stockcur+10 WHERE GTIN8=(?)",(new,))
return print('More stock has been ordered in as stocks were low')
else:
return
else:
temp = open('temp.txt', 'a')
temp.write('Product not found')
temp.write('\n')
temp.close()
return
I am currently getting the error sqlite3.OperationalError: near "(": syntax error, and have tried replacing the '(?)' with %s, (%s) and ? with no success, coming up with the following error messages:
sqlite3.OperationalError: near "12345670": syntax error // where 12345670 was the input represented by new
sqlite3.OperationalError: near "(": syntax error
sqlite3.OperationalError: near "?": syntax error
Is there another way of doing this or have I made a simple mistake?
None of the SQL statements you've written are valid SQL. Please consult the SQLite documentation for the valid syntax.
Briefly:
UPDATE GTINb SET stockcur=stockcur-1 WHERE GTIN8=(?)
SELECT stockcur from GTINb by (?)
SELECT restock from GTINb by (?)
should be
UPDATE GTINb SET stockcur=stockcur-1 WHERE GTIN8 = ?
SELECT stockcur FROM GTINb WHERE GTIN8 = ?
SELECT restock FROM GTINb WHERE GTIN8 = ?
although the first one will probably execute with the unneeded parentheses.
Once you have your SQL working you will find that the second two statements can be combined into
SELECT stockcur, restock FROM GTINb WHERE GTIN8 = ?
which I believe is what you were asking about.

PyQt ComboBox results not working in MySQL

I am writing a program in which two variables are selected from QCombobBoxes which are populated with results from a MySQL query. I then take these variable and insert them into a MySQLdb statement that inserts the variables into a different MySQL table. The first variable works fine, however on the second I get this error,
TypeError: 'NoneType' object has no attribute '__getitem__'
The code is identical for both variables, with the exception of different names
name = str(self.item_name.currentText())
cur.execute("SELECT item_id FROM Items WHERE name = '%s';"), name
db.commit()
results = cur.fetchone()
item_name = results[0]
personnel_name = str(self.purchaser_name.currentText())
cur.execute("SELECT personnel_id FROM Personnel WHERE name = '%s';"), personnel_name
db.commit()
results = cur.fetchone()
purchaser_id = results[0]
After playing with it, it looks like cur.execute("SELECT item_id FROM Items WHERE name = '%s';"), name is inserting an extra pair of quotation marks around the value that replaces %s Does anyone know why it's doing this and how to stop it? I coded both variables exactly the same, and it seems that name is getting an extra pair of quotes from MySQL
This is code that populates QComboBox:
#Get list of items currently in the database
cur = db.cursor()
cur.execute("SELECT name FROM Items")
db.commit()
results = cur.fetchall()
for name in results:
self.item_name.addItem(name[0])
#Get list of purchaser names
cur.execute("SELECT name FROM Personnel")
db.commit()
results = cur.fetchall()
for name in results:
self.purchaser_name.addItem(name[0])
If I manually insert a variable, it works fine. ex: cur.execute("SELECT item_id FROM Items WHERE name = 'Wire';") Only when I use string formatting with %s does the error occurr.
c.execute("SELECT * FROM sometable WHERE some_condition=?","My Condition")
you should always use the ? placeholders for this kind of thing
[edit]
try 1. cur.execute("SELECT item_id FROM Items WHERE name = '%s';"%(name,))
or 2. cur.execute("SELECT item_id FROM Items WHERE name = %s;", (name,))
from my brief reading, I think that mysql driver will automatically quote %s arguments
my conclusion is that cur.execute("SELECT item_id FROM Items WHERE name = %s;", (name,)) is the most correct way to do this(to avoid injection etc).

Categories