Pythons Bottle with SQLITE3 - python

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

Related

How to read Interbase database with Cyrillic text content

I am using pyfirebirdsql version 0.8.5 to connect to Interbase database.
import firebirdsql
conn = firebirdsql.connect(
host='192.168.133.121',
database='E:\\test\test.gdb',
port=3050,
user='sysdba',
password='masterkey'
#charset="WIN1251"
#charset="UTF8"
)
cur = conn.cursor()
cur.execute("select column1 from table1")
for c in cur.fetchall():
print(c)
conn.close()
When I try to run the script I get the following:
Traceback (most recent call last):
File "123.py", line 15, in <module>
for c in cur.fetchall():
File "/usr/lib/python2.7/site-packages/firebirdsql/fbcore.py", line 291, in fetchall
return [tuple(r) for r in self._fetch_records]
File "/usr/lib/python2.7/site-packages/firebirdsql/fbcore.py", line 225, in _fetch_generator
stmt_handle, self._xsqlda)
File "/usr/lib/python2.7/site-packages/firebirdsql/wireprotocol.py", line 728, in _op_fetch_response
return self._parse_op_response() # error occured
File "/usr/lib/python2.7/site-packages/firebirdsql/wireprotocol.py", line 210, in _parse_op_response
raise OperationalError(message, gds_codes, sql_code)
firebirdsql.OperationalError: arithmetic exception, numeric overflow, or string truncation
Cannot transliterate character between character sets
Adding charset both "WIN1251" and "UTF8" doesn't solve the issue. Do you have any ideas?

mysql connector with python formating

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

KeyError while executing SQL with parameters

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)

Select statement in mysql using LIKE (pyqt5)

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

Python Cassandra Query LIKE

How can I populate data dynamically with LIKE queries
I tried this:
q1 = sesi.execute("SELECT * FROM document WHERE judul LIKE '%s' ", "cluster" )
But I get the following error:
Traceback (most recent call last): File "", line 1, in File "/var/www/app_arsip/flask/local/lib/python2.7/site-packages/cassandra/cluster.py", line 2012, in execute
return self.execute_async(query, parameters, trace, custom_payload, timeout, execution_profile, paging_state).result()
File "/var/www/app_arsip/flask/local/lib/python2.7/site-packages/cassandra/cluster.py", line 2049, in execute_async
future = self._create_response_future(query, parameters, trace, custom_payload, timeout, execution_profile, paging_state)
File "/var/www/app_arsip/flask/local/lib/python2.7/site-packages/cassandra/cluster.py", line 2109, in _create_response_future
query_string = bind_params(query_string, parameters, self.encoder)
File "/var/www/app_arsip/flask/local/lib/python2.7/site-packages/cassandra/query.py", line 826, in bind_params
return query % tuple(encoder.cql_encode_all_types(v) for v in params)
TypeError: not all arguments converted during string formatting
I hope someone can help me
Thank you
Change your query, remove single quote and enclose your parameter with []
q1 = sesi.execute("SELECT * FROM document WHERE judul LIKE %s", ["%cluster%"] )

Categories

Resources