Passing string variable to the Postgres LIKE query [duplicate] - python

This question already has answers here:
how to safely generate a SQL LIKE statement using python db-api
(3 answers)
Closed yesterday.
In my flask app I am trying to pass a string to the query below:
tag = "Abcd"
conn = get_db_connection()
cur = conn.cursor()
cur.execute("SELECT * FROM database WHERE message LIKE %s ESCAPE ''", (tag,))
data = cur.fetchall()
cur.close()
conn.close()
I receive blank result.
I use psycopg2. My Postgres database has message containing "Abcd" and it works fine if I simply do:
cur.execute("SELECT * FROM database WHERE message LIKE '%Abcd%'")
If I try to pass it as a variable "tag" is my syntax for LIKE query correct?

you need to add % in your tag.
Try this:
tag = '%Abcd%' #--->> change here, add %Abcd%
conn = get_db_connection()
cur = conn.cursor()
cur.execute("SELECT * FROM database WHERE message LIKE %s ESCAPE ''", (tag,))
data = cur.fetchall()
cur.close()
conn.close()

Related

how to insert string into query in python pymysql

I have a following query:
cursor = connection.cursor()
query = """
SELECT *
FROM `my_database`.table_a
"""
result = cursor.execute(query)
which works as expected. But I need to change my_database in cursor.execute. I try:
cursor = connection.cursor()
query = """
SELECT *
FROM %s.table_a
"""
result = cursor.execute(query, ("my_database",))
which gives an 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 ''my_database'.table_a at line 2")
how can I insert database name in cursor.execute please?
It is not possible to bind a database name (or any other database object name) using a placeholder in a prepared statement. This would be, among other problems, a security risk. However, you might be able to use an f-string here instead:
cursor = connection.cursor()
db_name = "my_database"
query = f"""
SELECT *
FROM {db_name}.table_a
"""
result = cursor.execute(query)
It should also be mentioned that the above is only SQL injection safe if you are certain that the database name is not coming from outside your own application.

Inserting Query Results into Singlestore Table with Python and Sqlalchemy

I have parameterized queries with f strings such that the queries will select some data from a series of tables and joins, and I want to insert the resulting set of data into another pre-created table (tables been designed to house these results).
Python executes the code but the query results never show up in my table.
Assuming target_table is already created in singlestore database:
qry_load = 'insert into target_table select * from some_tables'
conn = engine.connect()
trans = conn.begin()
try:
conn.execute(qry_load)
trans.commit()
except:
trans.rollback()
raise
The code executes and acts as if all is ok, but the data never shows up in the target table.
How do I see what singlestore is passing back to better debug what is happening within the database?
Just replace begin() with cursor() function:
conn = engine.connect()
trans = conn.cursor()
If not resolved
1- Verify structure of source and destination tables if they are same or not.
2- remove try ,except and rollback() block so you can know the actual error.
Ex.
qry_load = 'insert into target_table select * from some_tables'
conn = engine.connect()
trans = conn.cursor()
conn.execute(qry_load)
trans.commit()

PostgreSQL Error while executing sql command in Python

i've been trying to get some data from my db by using below code, but the code is not working. is there any mistake that i made in the code, if so how can i fix it.
NOTE: i took the below code from just a script not a django or flesk web app.
def db():
conn = psycopg2.connect(
"dbname=mydb user=postgres password=****** host=*.*.*.*")
cur = conn.cursor()
cur.execute("""SELECT * FROM MddPublisher""")
query_results = cur.fetchall()
print(query_results)
db()
ERROR: psycopg2.errors.UndefinedTable: relation "mddpublisher" does not exist LINE 1: SELECT * FROM MddPublisher
additionally,i want to show below code to prove that connection is ok. the problem is that i can't receive data from my db whenever i try to execute select command through python.
def print_tables():
conn = psycopg2.connect(
"dbname=mydb user=postgres password=***** host=*.*.*.*.*")
cur = conn.cursor()
cur.execute("""SELECT table_name FROM information_schema.tables
WHERE table_schema = 'public'""")
for table in cur.fetchall():
print(table)
print_tables()
OUTPUT:
('MddPublisher',)
This is probably an issue with case sensitivity. Postgresql names are usually normalized to lower case. However, when used inside double quotes, they keep their case. So, to access a table named MddPublisher you must write it like "MddPublisher".
All the gory details are in Section 4.1.1, Identifiers and Key Words in the Postgresql 14 docs.

PyMySQL - Using a string as cursor.execute argument [duplicate]

This question already has answers here:
Executing raw SQL against SQLite with Django results in `DatabaseError: near "?": syntax error`
(2 answers)
Variable table name in sqlite
(9 answers)
Closed 4 years ago.
My problem here involves passing a string inside cursor.execute below
import pymsyql
import json
connection = pymysql.connect(
host='localhost', user='u_u_u_u_u',
password='passwd', db='test',
charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor
)
def get_data(table):
try:
with connection.cursor() as cursor:
sql = """
SELECT * FROM %s;
"""
cursor.execute(sql, (table,))
result = cursor.fetchall()
return json.dumps([dict(ix) for ix in result])
except (TypeError, pymysql.err.ProgrammingError) as error:
print(error)
finally:
pass
get_data('table_1')
connection.close()
I get the 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 ''table_1'' at line 1")
It seems that execute does not want a string passed as an argument; when I enter a string directly, like cursor.execute(sql, ('table_1',)), I get the same error.
I'm puzzled as to what is causing the issue, the dual-quotes ''table_1'' are confusing. Can anyone tell me what's going on here?
You cannot pass a table name as a parameter, alas. You have to munge it into the query string:
sql = """
SELECT * FROM `{0}`;
""".format(table)
cursor.execute(sql)

Dynamic table names within MYSQL statement (Google Cloud SQL)

I am trying to drop/delete a table from within Google Cloud SQL using Python (App Engine) but I want the table name to be based on a variable, for simplicity I am using 'hello' here. For some reason it is throwing back an error at me: "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 '-IN' at line 1"
I tried the following:
tabNameShort = 'hello'
cursor = conn.cursor()
cursor.execute('DROP TABLE IF EXISTS %s', (tabNameShort))
conn.commit()
I also tried:
tabNameShort = 'hello'
cursor = conn.cursor()
cursor.execute('DROP TABLE IF EXISTS ' + tabNameShort)
conn.commit()
Any suggestions?
try this:
tabNameShort = 'hello'
cursor = conn.cursor()
cursor.execute('DROP TABLE IF EXISTS `%s`' % tabNameShort)
conn.commit()
A warning: appending the table name directly using '+' can result in an SQL injection vulnerability, if the table name is derived, directly or indirectly, from user input.

Categories