I wrote a simple script that shows the user a letter and he has to write a human name that starts with the same letter, but I am having a problem automatically compensating for the column name using a variable... Is there a suggestion?
How do I replace the column name with the variable let?
import random
import mysql.connector
while True:
letters = "AB"
let = random.choice(letters)
print(let)
human = input("Human : ")
db = mysql.connector.connect(host = 'localhost',
user = 'root',
password = '',
database = 'test')
mycs = db.cursor()
mycs.execute(" SELECT * FROM human WHERE {} = {}".format(let,human))
data = mycs.fetchall()
if data:
print("Name exists")
else:
print("Name does not exist")
mycs.close()
The error:
B
Human : brad
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\t.py", line 16, in <module>
mycs.execute(" SELECT * FROM human WHERE {} = {}".format(let,human))
File "C:\Program Files\Python39\lib\site-packages\mysql\connector\cursor.py", line 568, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "C:\Program Files\Python39\lib\site-packages\mysql\connector\connection.py", line 686, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "C:\Program Files\Python39\lib\site-packages\mysql\connector\connection.py", line 573, in _handle_result
raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column 'brad' in 'where clause'
You just need to put the constant in the to the query between single quotes:
(" SELECT * FROM human WHERE {} = '{}'".format(let,human))
Related
c.execute('show tables')
for i in c:
print(i)
t=input('enter exact table name')
n=0
c.execute('show columns from {}'.format(t))
records=c.fetchall()
print(records)
for i in records:
n=n+1
a=1
data=''
while a!=0:
for i in range(n):
v=input("enter data")
if i==n-1:
data=data+v
else:
data=data+v+','
print(data)
print('insert into {} values{}'.format(t,data))
c.execute('insert into {} values({})'.format(t,data))
in this code i am getting the following error:
Traceback (most recent call last):
File "C:\Users\subra\OneDrive\Desktop\netflix.py", line 62, in <module>
create_input()
File "C:\Users\subra\OneDrive\Desktop\netflix.py", line 51, in create_input
c.execute('insert into {} values{}'.format(t,data))
File "C:\Users\subra\AppData\Local\Programs\Python\Python38\lib\site-packages\mysql\connector\cursor.py", line 569, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "C:\Users\subra\AppData\Local\Programs\Python\Python38\lib\site-packages\mysql\connector\connection.py", line 599, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "C:\Users\subra\AppData\Local\Programs\Python\Python38\lib\site-packages\mysql\connector\connection.py", line 487, in _handle_result
raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column 'subru' in 'field list'
can anyone help me out on how to avoid this error
i have also made sure that there is only 1 table and that is the one i am inserting
this is the output that i get including the input vales:
>>>('hellopython',)
>>>enter exact table namehellopython
>>>[('student', b'varchar(30)', 'YES', '', None, ''), ('rollno', b'varchar(30)', 'YES', '', None,'')]
>>>enter datasubru
>>>enter data29
>>>(subru,29)
>>>insert into hellopython values(subru,29)
***Traceback (most recent call last):
File "C:\Users\subra\OneDrive\Desktop\netflix.py", line 62, in <module>
create_input()
File "C:\Users\subra\OneDrive\Desktop\netflix.py", line 51, in create_input
c.execute('insert into {} values{}'.format(t,data))
File "C:\Users\subra\AppData\Local\Programs\Python\Python38\lib\site-packages\mysql\connector\cursor.py", line 569, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "C:\Users\subra\AppData\Local\Programs\Python\Python38\lib\site-packages\mysql\connector\connection.py", line 599, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "C:\Users\subra\AppData\Local\Programs\Python\Python38\lib\site-packages\mysql\connector\connection.py", line 487, in _handle_result
raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column 'subru' in 'field list'***
You are missing quotes around the data.
So MySQL thinks that subru is not a name. instead he thninks it is a column name
if i==n-1:
data=data+"'"+v+ "'"
else:
data=data+"'"+v+ "'"+','
print(data)
print('insert into {} values{}'.format(t,data))
c.execute('insert into {} values({})'.format(t,data))
I am getting KeyError while running below code. I am trying to pass parameters using separate parameters variable.
Code:
import teradata
host,username,password = 'hostname','uname', 'pwd'
udaExec = teradata.UdaExec (appName="APtest", version="1.0", logConsole=False)
connect = udaExec.connect(method="odbc",system=host, username=username, password=password, dsn="dsnname")
val1='NULL'
val2='NULL'
parameters={'param1':val1, 'param2': val2}
qry="""
SELECT number
FROM table
WHERE number = %(param1)s
AND col=%(param2)s
"""
connect.execute(qry, parameters)
Error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/tmp/lib/python2.7/site-packages/teradata/udaexec.py", line 675, in execute
self.internalCursor.execute(query, params, **kwargs)
File "/tmp/lib/python2.7/site-packages/teradata/udaexec.py", line 745, in execute
self._execute(self.cursor.execute, query, params, **kwargs)
File "/tmp/lib/python2.7/site-packages/teradata/udaexec.py", line 787, in _execute
logParamCharLimit)
File "/tmp/lib/python2.7/site-packages/teradata/udaexec.py", line 875, in _getParamsString
if isinstance(params[0], (list, tuple)):
KeyError: 0
If i write the query in below manner then it works but i have very long list of parameters therefore need it in separate parameter variable.
This works:
qry="""
SELECT number
FROM table
WHERE number = '%s'
AND col='%s'
""" % (val1, val2)
Apparently, teradata does not support dictionaries for parameters. Use a list instead.
parameters = [val1, val2]
qry="""
SELECT number
FROM table
WHERE number = %s
AND col=%s
"""
connect.execute(qry, parameters)
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,)):
...
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 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.