Not able to parameterize LIMIT and OFFSET in sqlite3 - python-3.x

Why following code is giving syntax error "sqlite3.OperationalError: near "?": syntax error"
import sqlite3
connection = sqlite3.connect('data.db')
cursor = connection.cursor()
table = "device_store"
uuid = "bbebe39e-fe2e-4817-b022-a3ef13bd6283"
page = 1
POSTS_PER_PAGE = 10
query = "SELECT * FROM ? WHERE uuid=? LIMIT ? OFFSET ?"
result = cursor.execute(query, (table, uuid, POSTS_PER_PAGE, 0))
rows = result.fetchall()
connection.close()
print("==>> Printing rows <<==")
print(rows)

The error is caused by the placeholder in FROM ?, not the others. Table names can't be passed as parameters, they have to be hardcoded in the statement.

Related

Argument must be str not tuple

i need to load only the data from database by todays date.
date column in database is in TEXT...
''code to load all the data from database''
def load_database(self):
today_date = current_date[0:11]
while self.workingpatient_table.rowCount() > 0:
self.workingpatient_table.removeRow(0)
conn = sqlite3.connect(r'mylab.db')
content = ("SELECT * FROM daily_patients where date=?",(today_date))
result = conn.execute(content)
for row_index,row_data in enumerate(result):
self.workingpatient_table.insertRow(row_index)
for column_index,column_data in enumerate(row_data):
self.workingpatient_table.setItem(row_index,column_index,QTableWidgetItem(str(column_data)))
conn.close()
''when i run the program i get following error ''
result = conn.execute(content)
TypeError: argument 1 must be str, not tuple
any possible solution?
Change your line from
content = ("SELECT * FROM daily_patients where date=?",(today_date))
result = conn.execute(content)
to
content = ("SELECT * FROM daily_patients where date=?",(today_date, ))
result = conn.execute(*content)

How to send in python params (which is string) into SQL question on DB2

I want to write function which receive parameter as string which should be used inside SQL statement for DB2 database. Then I need to take row by row and do smth in each loop step:
import ibm_db
conn_str = 'database=xxx;hostname=x.x.x.x;port=xxxx;protocol=TCPIP;UID=xxxxx;pwd=secret;'
ibm_db_conn = ibm_db.connect(conn_str,'','')
def question_to_db(tel : string):
sql = "SELECT * from mper where mper.tel = ?"
sql2 = ibm_db.prepare(ibm_db_conn, sql)
ibm_db.bind_param(sql2, 1, tel, ibm_db.SQL_PARAM_INPUT, ibm_db.SQLCHAR)
stmt = ibm_db.exec_immediate(ibm_db_conn, sql2)
row = ibm_db.fetch_both(stmt)
while row != False
do_smth_with_row ....
row = ibm_db.fetch_both(stmt)
return(True)
After run of program I receive error:
stmt = ibm_db.exec_immediate(ibm_db_conn, sql2)
Exception: statement must be a string or unicode
I'm looking for any solution of my problem. I can't find any exmaples with string and fetching rows :(
Any one can help me ? Thanks in advance.
Well, the Db2 Python API documentation has an example. The problem is that your are mixing different functions. You either
execute_immediate: A string is passed in to be executed once as SQL statement.
prepare and execute: You first prepare a string as SQL statement to be executed. When prepared, you can execute that statement once or many times.
Something like this should work:
sql_stmt = "SELECT * from mper where mper.tel = ?"
stmt = ibm_db.prepare(ibm_db_conn, sql_stmt)
ibm_db.bind_param(stmt, 1, tel)
try:
ibm_db.execute(stmt)
except:
print(ibm_db.stmt_errormsg())

Pandas Oracle query gives "ORA-00911: invalid character"

Hello I am trying to execute the following Oracle Query. I confirmed i can successfully connect to the database using cx_Oracle but my query is not executing. This is a large table and i am trying to limit the number of rows to 10
query1 = """
select *
from
(select *
from some_table
)
where rownum < 10;
"""
df_ora1 = pd.read_sql(query1, con=connection1)
I am getting the following error but cant figure out what the invalid character is!
DatabaseError: ORA-00911: invalid character
Please help!
Remove the semi-colon from the SQL statement. Semi-colons are not part of SQL.
query1 = """ select * from (select * from some_table ) where rownum < 10 """

After integer greater than 9 Incorrect number of bindings supplied. The current statement uses 1, and there are 2 supplied

def delete_Link(id):
connection = sql_Connect()
cursor = connection.cursor()
cursor.execute("DELETE FROM table WHERE id =?", str(id))
connection.commit()
After iterating over rows once the table id is greater than 9 I receive the following error
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 2 supplied.
Change str(id) to (str(id), ) like in this example:
import sqlite3
def delete_link(id):
connection = sqlite3.connect('test.db')
cursor = connection.cursor()
cursor.execute("DELETE FROM t WHERE id =?", (str(id),))
connection.commit()
print('Deleted ' + str(id))
if __name__ == '__main__':
for id in range(1, 11):
delete_link(id)
Check out some examples of .execute() on https://docs.python.org/2/library/sqlite3.html. It shows how you can send a tuple to that method in parameterized query.
def delete_Link(id):
connection = sql_Connect()
cursor = connection.cursor()
cursor.execute("DELETE FROM table WHERE id =?", [id])
connection.commit()
Changed the original snippet to include [] instead of () which seems to have fixed the issue. Hope this helps some others.

update statement using loop over tuple of query and data fails in psycopg2

I have created a mini functional pipeline which creates an update statement with regex and then passes the statement and the data to pycopg2 to execute.
If I copy paste the statement outside of the loop it works, if I try to loop over all statements I get an error.
# Function to create statement
def psycopg2_regex_replace_chars(table, col, regex_chars_old, char_new):
query = "UPDATE {} SET {} = regexp_replace({}, %s , %s, 'g');".format(table, col, col)
data = (regex_chars_old, char_new)
return (query, data)
# Create functions with intelligible names
replace_separators_with_space = partial(psycopg2_regex_replace_chars,regex_chars_old='[.,/[-]]',char_new=' ')
replace_amper_with_and = partial(psycopg2_regex_replace_chars, regex_chars_old='&', char_new='and')
# create funcs_list
funcs_edit = [replace_separators_with_space,
replace_amper_with_and]
So far, so good.
This works
stmt = "UPDATE persons SET name = regexp_replace(name, %s , %s, 'g');"
data = ('[^a-zA-z0-9]', ' ')
cur.execute(stmt, data)
conn.commit()
This fails
tables = ["persons"]
cols = ["name", "dob"]
for table in tables:
for col in cols:
for func in funcs_edit:
query, data = func(table=table, col=col)
cur.execute(query, data)
conn.commit()
error
<ipython-input-92-c8ba5d469f88> in <module>
6 for func in funcs_edit:
7 query, data = func(table=table, col=col)
----> 8 cur.execute(query, data)
9 conn.commit()
ProgrammingError: function regexp_replace(date, unknown, unknown, unknown) does not exist
LINE 1: UPDATE persons SET dob = regexp_replace(dob, '[.,/[-]]' , ' ...
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.```

Resources