Select statement in mysql using LIKE (pyqt5) - python

Newbie here. Id like to ask What could possibly wrong with this code:
'SELECT * FROM A3A_SIS.customer_info WHERE cust_name LIKE %' +self.le_ci_search.text()+ '%'
This line returns an error of this:
TypeError: a bytes-like object is required, not 'tuple'
I am trying to search a column name where theres a word lopez in it.
UPDATE #1:
I use this code as suggested:
def CustSearch(self):
search_text = '%{}%'.format(self.le_ci_search.text())
con = mdb.connect(user='root', passwd='password',
host='localhost', database='A3A_SIS')
with con:
cur = con.cursor()
query = ('SELECT * FROM A3A_SIS.customer_info WHERE cust_name LIKE %s', (search_text))
if cur.execute(query):
QMessageBox.information(self, "Announcement.","Data was found!")
else:
QMessageBox.information(self, "Announcement.","No data was found!")
con.close()
I got this error:
Traceback (most recent call last):
File "/Users/anthonygaupo/Desktop/A3ASIS/A3A_Func.py", line 409, in
CustSearch
if cur.execute(query):
File
"/Users/anthonygaupo/anaconda3/lib/python3.6/site-packages/MySQLdb/cursors.py",
line 250, in execute
self.errorhandler(self, exc, value)
File
"/Users/anthonygaupo/anaconda3/lib/python3.6/site-packages/MySQLdb/connections.py",
line 50, in defaulterrorhandler
raise errorvalue
File
"/Users/anthonygaupo/anaconda3/lib/python3.6/site-packages/MySQLdb/cursors.py",
line 247, in execute
res = self._query(query)
File
"/Users/anthonygaupo/anaconda3/lib/python3.6/site-packages/MySQLdb/cursors.py",
line 411, in _query
rowcount = self._do_query(q)
File
"/Users/anthonygaupo/anaconda3/lib/python3.6/site-packages/MySQLdb/cursors.py",
line 374, in _do_query
db.query(q)
File
"/Users/anthonygaupo/anaconda3/lib/python3.6/site-packages/MySQLdb/connections.py",
line 277, in query
_mysql.connection.query(self, query)
TypeError: a bytes-like object is required, not 'tuple'
I am MYSQL workbench

You would need to put the search text, including the % characters, in quotes.
But you should not do this. Assemble the value outside of the SQL statement and use parameter substitution:
query = '%{}%'.format(self.le_ci_search.text())
cursor.execute('SELECT * FROM A3A_SIS.customer_info WHERE cust_name LIKE %s', (query,))
Edit
You're creating a single tuple and passing it to the cursor as the query. What I said to do is to create a string, and pass that plus the parameter to the cursor:
cur = con.cursor()
query = 'SELECT * FROM A3A_SIS.customer_info WHERE cust_name LIKE %s'
if cur.execute(query, (search_text,)):
...

Related

TypeError: not enough arguments for format string python pymysql (Delete row)

This is my code...
sql = "DELETE FROM %s WHERE %s < NOW() - INTERVAL %s YEAR"
delete_list = [{'TABLE_NM': 'tb_user', 'COLUMN_NM': 'CRTE_DT', 'YEAR': 3}]
cursor.executemany(sql, delete_list)
connection.commit()
python run~
Error code :
Traceback (most recent call last):
File "~PATH", line 30, in <module>
cursor.executemany(sql, (delete_list['TABLE_NM'], delete_list['COLUMN_NM'], delete_list['YEAR']))
File "~PATH\anaconda3\Lib\site-packages\pymysql\cursors.py", line 182, in executemany
self.rowcount = sum(self.execute(query, arg) for arg in args)
File "~PATH"\anaconda3\Lib\site-packages\pymysql\cursors.py", line 182, in <genexpr>
self.rowcount = sum(self.execute(query, arg) for arg in args)
File "~PATH\anaconda3\Lib\site-packages\pymysql\cursors.py", line 146, in execute
query = self.mogrify(query, args)
File "~PATH\anaconda3\Lib\site-packages\pymysql\cursors.py", line 125, in mogrify
query = query % self._escape_args(args, conn)
TypeError: not enough arguments for format string
Can anyone help this error...?
sql = "DELETE FROM tb_user WHERE CRTE_DT < NOW() - INTERVAL %s YEAR"
delete_list = [3]
cursor.executemany(sql, delete_list)
connection.commit()
column and table should rarely be variable.

Using prepared queries to change the column in a MySQL update command Python 3.5

I'm trying to write a function that takes 3 values, the column to edit, the value to insert, and the id of the row (a hash in this case). However I get a standard "There's an error on your SQL Syntax"
def _alter_material_prop(self, hash, key, val):
sql = "UPDATE `materials` SET "+key+" = %s WHERE `materials`.`hashkey` = %s"
self.cursor.execute(sql, (val, hash))
self.db.commit()
This is my sql injectable code that functions.
Here is how I would like to do it:
def _alter_material_prop(self, hash, key, val):
sql = "UPDATE `materials` SET %s = %s WHERE `materials`.`hashkey` = %s"
self.cursor.execute(sql, (key, val, hash))
self.db.commit()
But this gives the following error msg:
Traceback (most recent call last):
File "/Users/Nate/PycharmProjects/mofdb-insert-mofs/mofdb_interface_tests.py", line 478, in test_alter_mat_prop
mofdb._alter_material_prop(hashkey, "PLD", 1337.0)
File "/Users/Nate/PycharmProjects/mofdb-insert-mofs/mofdb_interface.py", line 227, in _alter_material_prop
self.cursor.execute(sql, (key, val, hash))
File "/Users/Nate/PycharmProjects/mofdb-insert-mofs/venv/lib/python3.5/site-packages/mysql/connector/cursor.py", line 559, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "/Users/Nate/PycharmProjects/mofdb-insert-mofs/venv/lib/python3.5/site-packages/mysql/connector/connection.py", line 494, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "/Users/Nate/PycharmProjects/mofdb-insert-mofs/venv/lib/python3.5/site-packages/mysql/connector/connection.py", line 396, in _handle_result
raise errors.get_exception(packet)
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 ''PLD' = 1337.0 WHERE `materials`.`hashkey` = '43ba34f38db8ec0f20cb058853275535ea' at line 1

pymysql.err.ProgrammingError 1064 when executing command

I just can't see a reason for this error. I have tried the same SQL in phpMyAdmin and it works perfectly fine, but fails when trying from Python.
Python code with SQL query:
cursor.execute("UPDATE marketPricesAvg SET avg%sh=(SELECT AVG(price) FROM marketPrices WHERE itemName = %s AND ((NOW() - marketPrices.datetime) < %s) WHERE itemName = %s)", (time, itemName, time_sec, itemName))
Error message:
Traceback (most recent call last):
File "/root/marketprices/insert.py", line 42, in <module>
calculate_avg(itemName, time)
File "/root/marketprices/insert.py", line 29, in calculate_avg
cursor.execute("UPDATE marketPricesAvg SET avg%sh=(SELECT AVG(price) FROM marketPrices WHERE itemName = %s AND ((NOW() - marketPrices.datetime) < %s) WHERE itemName = %s)", (time, itemName, time_sec, itemName))
File "/usr/local/lib/python2.7/dist-packages/pymysql/cursors.py", line 170, in execute
result = self._query(query)
File "/usr/local/lib/python2.7/dist-packages/pymysql/cursors.py", line 328, in _query
conn.query(q)
File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 516, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 727, in _read_query_result
result.read()
File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 1066, in read
first_packet = self.connection._read_packet()
File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 683, in _read_packet
packet.check_error()
File "/usr/local/lib/python2.7/dist-packages/pymysql/protocol.py", line 220, in check_error
err.raise_mysql_exception(self._data)
File "/usr/local/lib/python2.7/dist-packages/pymysql/err.py", line 109, in raise_mysql_exception
raise errorclass(errno, errval)
pymysql.err.ProgrammingError: (1064, u"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 'WHERE itemName = 'Aluminium')' at line 1")
Thank you for any ideas.
Your query fully qualified would look something like
UPDATE marketPricesAvg
SET avg1234 = (
SELECT AVG(price) FROM marketPrices
WHERE itemName = 'Aluminium' AND
((NOW() - marketPrices.datetime) < '100') WHERE itemName = 'Aluminium'
);
Edit:
Should be
(NOW() - marketPrices.datetime) < %s) WHERE itemName = %s
The final parentheses is misplaced

Pythons Bottle with SQLITE3

I have been trying to practise Bottle Py. There is a tutorial about making an APP: TODO.
It works fine. But If task id exceeds 1 character that means 10 instead of 1,2,3,4,5,6,7,8,9
It shows error like below.
ProgrammingError('Incorrect number of bindings supplied. The current
statement uses 1, and there are 2 supplied.',)
Code is:
#route('/edit/<no:int>', method='GET')
def edit_item(no):
if request.GET.save:
edit = request.GET.task.strip()
status = request.GET.status.strip()
if status == 'open':
status = 1
else:
status = 0
conn = sqlite3.connect('todo.db')
c = conn.cursor()
c.execute("UPDATE todo SET task = ?, status = ? WHERE id LIKE ?", (edit, status, no))
conn.commit()
return '<p>The item number %s was successfully updated</p>' % no
else:
conn = sqlite3.connect('todo.db')
c = conn.cursor()
c.execute("SELECT task FROM todo WHERE id LIKE ?", (str(no)))
cur_data = c.fetchone()
return template('edit_task', old=cur_data, no=no)
Tracebacks:
1.
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/bottle.py", line 862, in _handle
return route.call(**args)
File "/usr/lib/python2.7/dist-packages/bottle.py", line 1737, in wrapper
rv = callback(*a, **ka)
File "todo.py", line 67, in edit_item
c.execute('SELECT task FROM todo WHERE id LIKE ?', no)
ValueError: parameters are of unsupported type
2.
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/bottle.py", line 862, in _handle
return route.call(**args)
File "/usr/lib/python2.7/dist-packages/bottle.py", line 1737, in wrapper
rv = callback(*a, **ka)
File "todo.py", line 67, in edit_item
c.execute('SELECT task FROM todo WHERE id LIKE ?', (no))
ValueError: parameters are of unsupported type
What to do?
This might happen because the execute function will unpack your second parameter when you do (str(no)) the outer () will not convert your tuple, you need to do (str(no),) if you have only one element in the tuple.
For instance, since it recognized as string, it will unpack "10" it into ("1", "0")

python:mysql error, "Incorrect string value: '\\xF0\\x9F\\x87\\xBA\\xF0\\x9F...'

python program ,insert data in mysql table:
is_exist_table_sql = "SHOW TABLES LIKE 'fb_public_figure_posts'"
if cur.execute(is_exist_table_sql) == 0:
create_sql = """CREATE TABLE fb_public_figure_posts(Post_ID varchar(32), Permalink varchar(128), Create_time varchar(32), Updated_time varchar(32), Author varchar(32),
Author_ID bigint, Message text, Link varchar(1024), Likes int, Comments int, pf_ID bigint, foreign key(pf_ID) references fb_public_figure_info(ID))"""
cur.execute(create_sql)
db_data = posts
if type == "public_figure_posts":
for item in db_data:
if "'" in item["message"]:
item["message"] = str(item["message"]).replace("'","\\\'")
elif '"' in item["message"]:
item["message"] = str(item["message"]).replace('"','\\\"')
is_exist_id_sql = "select * from fb_public_figure_posts where Post_ID = '" + item['id'] + "'"
if cur.execute(is_exist_id_sql) == 0:
insert_sql = "INSERT INTO fb_public_figure_posts VALUES ('{0}','{1}','{2}','{3}','{4}',{5},'{6}','{7}',{8},{9},{10})".format(item['id'],item['permalink_url'],item['created_time'],item['updated_time'],item['from']['name'],item['from']['id'],item['message'],item['link'],item['likes']['summary']['total_count'],item['comments']['summary']['total_count'],public_figure_id)
print(insert_sql)
cur.execute(insert_sql)
when running , it errors:
pymysql.err.InternalError: (1366, "Incorrect string value: '\\xF0\\x9F\\x87\\xBA\\xF0\\x9F...' for column 'Message' at row 1")
it point that the sentence error:
Traceback (most recent call last):
File "C:/Python/PyCharmProject/FaceBookCrawl/FBCrawl.py", line 286, in <module>
publicfigure_download.public_figure_posts_storage(public_figure_name)
INSERT INTO fb_public_figure_posts VALUES ('153080620724_10158392447835725','https://www.facebook.com/DonaldTrump/posts/10158392447835725:0','2017-01-01T04:59:07+0000','2017-01-23T19:52:49+0000','Donald J. Trump',153080620724,'‪TO ALL AMERICANS-‬
File "C:\Python\PyCharmProject\FaceBookCrawl\publicfigure_download.py", line 103, in public_figure_posts_storage
‪#HappyNewYear & many blessings to you all! Looking forward to a wonderful & prosperous 2017 as we work together to #MAGA🇺🇸‬','https://www.facebook.com/DonaldTrump/photos/a.488852220724.393301.153080620724/10158392447835725/?type=3',158710,11045,153080620724)
mysql_manage().public_figure_db_manage(type, posts, public_figure_id, public_figure_name)
File "C:\Python\PyCharmProject\FaceBookCrawl\database_manage.py", line 47, in public_figure_db_manage
cur.execute(insert_sql)
File "C:\Python\Python36\lib\site-packages\pymysql\cursors.py", line 166, in execute
result = self._query(query)
File "C:\Python\Python36\lib\site-packages\pymysql\cursors.py", line 322, in _query
conn.query(q)
File "C:\Python\Python36\lib\site-packages\pymysql\connections.py", line 835, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "C:\Python\Python36\lib\site-packages\pymysql\connections.py", line 1019, in _read_query_result
result.read()
File "C:\Python\Python36\lib\site-packages\pymysql\connections.py", line 1302, in read
first_packet = self.connection._read_packet()
File "C:\Python\Python36\lib\site-packages\pymysql\connections.py", line 981, in _read_packet
packet.check_error()
File "C:\Python\Python36\lib\site-packages\pymysql\connections.py", line 393, in check_error
err.raise_mysql_exception(self._data)
File "C:\Python\Python36\lib\site-packages\pymysql\err.py", line 107, in raise_mysql_exception
raise errorclass(errno, errval)
pymysql.err.InternalError: (1366, "Incorrect string value: '\\xF0\\x9F\\x87\\xBA\\xF0\\x9F...' for column 'Message' at row 1")
Process finished with exit code 1
in conclusion, it shows:
pymysql.err.InternalError: (1366, "Incorrect string value: '\\xF0\\x9F\\x87\\xBA\\xF0\\x9F...' for column 'Message' at row 1")
could you please help me for that
You actually have two problems here. The first one is that you're trying to insert a string containing characters that are not supported by your database/table/field encoding - the catch is that MySQL's "utf-8" encoding is NOT really utf8 compliant (surprise, surprise...). The linked SO question gives full explanations, you can also check this for a migration procedure.
Your second issue - which AFAICT isn't responsible for the problem you describe but will cause quite a few other problems anyway - is that you're not using your db connector properly. This makes your code uselessly complicated and quite brittle - proper escaping is a pain as you might have noticed, so better to let the db connector do the job -, but also opens your app to SQL injection attacks. The cure here is simple: use prepared statements. This is actually much simpler than not using them and will kill two birds with one stone.

Categories

Resources