This question already has answers here:
How can I bind a list to a parameter in a custom query in SQLAlchemy?
(9 answers)
Closed 2 years ago.
my table in a database is as follow
Username city Type
Anna Paris abc
Marc london abc
erica rome AF
Sara Newyork cbd
silvia paris AD
I have a list contains string values
typelist = {'abc', 'cbd'}
and i want to query my database using sqlalchemy , to get data from a table where a column type equals the values in the list :
Username city Type
Anna Paris abc
Marc london abc
Sara Newyork cbd
im trying this code
sql = "SELECT * FROM table WHERE data IN :values"
query = sqlalchemy.text(sql).bindparams(values=tuple(typelist))
conn.engine.execute(query)
but it return just one value from the typelist not all the list values .
Username city Type
Sara Newyork cbd
sql = "SELECT * FROM table WHERE data IN :values"
query = sqlalchemy.text(sql).bindparams(sqlalchemy.bindparam("values", expanding=True))
conn.engine.execute(query, {"values": typelist})
Reference: https://docs.sqlalchemy.org/en/13/core/sqlelement.html#sqlalchemy.sql.expression.bindparam.params.expanding
My solution will work but you will need to format your string like this
sql = "SELECT * FROM table WHERE data IN ('data1', 'data2', 'data3')"
No need to use bind param here. Use this if you dont get any proper solution
You could use a dynamic SQL approach where you create a string from your list values and add the string to your SELECT statement.
queryList = ['abc', 'def']
def list_to_string(inList):
strTemp = """'"""
for x in inList:
strTemp += str(x) + """','"""
return strTemp[:-2]
sql = """SELECT * FROM table WHERE data in (""" + list_to_string(queryList) + """)"""
print(sql)
Related
I am using jupyter notebook to access Teradata database.
Assume I have a dataframe
Name Age
Sam 5
Tom 6
Roy 7
I want to let the whole column "Name" content become the WHERE condition of a sql query.
query = '''select Age
from xxx
where Name in (Sam, Tom, Roy)'''
age = pd.read_sql(query,conn)
How to format the column so that the whole column can be insert to the sql statement automatically instead of manually paste the column content?
Join the Name column and insert into the query using f-string:
query = f'''select Age
from xxx
where Name in ({", ".join(df.Name)})'''
print(query)
select Age
from xxx
where Name in (Sam, Tom, Roy)
I am trying to get column names from my postgres sql table using psycopg2 but it is returning unordered column list not same as how columns are shown in table.
This is how database table look when saved as pandas dataframe:
cur.execute("Select * from actor")
tupples = cur.fetchall()
cur.execute("select column_name from information_schema.columns where table_name = 'actor'")
column_name = cur.fetchall()
df = pd.DataFrame(tupples,columns = column_name)
(actor_id,) (last_update,) (first_name,) (last_name,)
1 PENELOPE GUINESS 2006-02-15 04:34:33
2 NICK WAHLBERG 2006-02-15 04:34:33
3 ED CHASE 2006-02-15 04:34:33
4 JENNIFER DAVIS 2006-02-15 04:34:33
5 JOHNNY LOLLOBRIGIDA 2006-02-15 04:34:33
This is how database table looked like when i see in pgadmin2:
I just want the column_name to return the column names of sql table as shown in image.
I have a dataframe like this
Name age city
John 31 London
Pierre 35 Paris
...
Kasparov 40 NYC
I would like to select data from redshift city table using sql where city are included in city of the dataframe
query = select * from city where ....
Can you help me to accomplish this query?
Thank you
Jeril's answer is going to right direction but not complete. df.unique() result is not a string it's series. You need a string in your where clause
# create a string for cities to use in sql, the way sql expects the string
unique_cities = ','.join("'{0}'".format(c) for c in list(df['city'].unique()))
# output
'London','Paris'
#sql query would be
query = f"select * from city where name in ({unique_cities})"
The code above is assuming you are using python 3.x
Please let me know if this solves your issue
You can try the following:
unique_cities = df['city'].unique()
# sql query
select * from city where name in unique_cities
I'm trying to create a SELECT statement that selects rows where NAME is max. 5 characters and the . is in the NAME.
I only want the first, so I'm including a LIMIT 1 to the statement.
I have worked with the following
searchstring = "."
sql = "SELECT * FROM Table WHERE NAME LIKE %s LIMIT 1"
val = (("%"+searchstring+"%"),)
cursor.execute(sql, val)
But I'm not sure how to incorporate the length of NAME in my statement.
My "Table" is as follows:
ID NAME
1 Jim
2 J.
3 Jonathan
4 Jack M.
5 M.S.
So based on the table above, I would expect row 2 and 5 to be selected.
I could select all, and loop through them. But as I only want the first, I'm thinking I would prefer a SQL statement?
Thanks in advance.
You can use CHAR_LENGTH function along with LIKE:
SELECT * FROM Table WHERE name LIKE '%.%' AND CHAR_LENGTH(name) <= 5 LIMIT 1
Try LEN()
Select LEN(result string);
This will return the length of string. but this will count spaces also. Try removing it with LTRIM().
Oracle SQL
SELECT * FROM Table WHERE name LIKE '%.%' AND LENGTH(name) < 6 and rownum < 2
Base on the sql language(oracle, mysql, sql server, etc) use
length() or char_length()
rownum or limit
This is my data:
mylist=["happy" , "sad", "cute"]
country = 'US'
mytable
id terms values
1 happy 3
2 sad 4
3 angry 5
in python my sql query looks like this:
myquery=
"""select * from mytable where country = '%s' and terms is in ('%s', '%s');""" %(country, tuple(mylist))
error not enough arguments for format string.
python's db adapter has provided the parameter formatting, you only need to use it:
cursor.execute('select * from mytable where terms in %s and country = %s;', (tuple(mylist), country))
See more: https://www.python.org/dev/peps/pep-0249/#id14