I am trying to use one query output into other. but not getting the correct result. Can you please help me how to do this?
Example:
query1 = "select distinct lower(tablename) as tablename from medaff.imedical_metadata where object_type = 'View'"
output of above query is :
tablename
vw_mdcl_insght
vw_fbms_interactions
I want to use above output in other query. Something like this-
query2 = "select * from medaff.imedical_business_metadata where objectname in ('vw_mdcl_insght', 'vw_fbms_interactions')"
How to do this part in python?
I am using below code to run the query:
conn = redshift_conn()
with conn.cursor() as cur:
query1 = "select distinct lower(tablename) as tablename from medaff.imedical_metadata where object_type = 'View'"
cur.execute(sql_query)
result = cur.fetchall()
print(result)
conn.commit()
query2 = "select * from medaff.imedical_business_metadata where objectname in ('vw_mdcl_insght', 'vw_fbms_interactions')"
cur.execute(sql_query)
result = cur.fetchall()
print(result)
conn.commit()
I think you can just use an in query:
select ibm.*
from medaff.imedical_business_metadata ibm
where ibm.objectname in (select lower(im.tablename) as tablename
from medaff.imedical_metadata im
where im.object_type = 'View'
);
It is better to let the database do the work.
I used the below code:
query = "select distinct lower(tablename) from medaff.imedical_metadata where object_type = 'View'"
cur.execute(query)
res = cur.fetchall()
print(res)
res = tuple([item[0] for item in res])
res = str(res)
Related
Trying to delete some of the table entries by using pyodbc in database results in nothing happening. I know for sure that database connection is working as intended, can select data. Perhaps any suggestions what could be the cause?
get_user_id = conn.cursor()
get_user_id.execute('''
SELECT b.UserId
FROM Bindery b
INNER JOIN ActiveUser au
ON au.Id = b.UserId
WHERE au.UserId = ?
''', user_to_kick)
id_list = [id[0] for id in get_user_id.fetchall()]
delete_user = conn.cursor()
#delete from bindery first
delete_user.execute('''
DELETE FROM Bindery
WHERE UserId in (?)
''', id_list)
conn.commit
#delete from active user list
delete_user.execute('''
DELETE FROM ActiveUser
WHERE UserId = ?
''', user_to_kick)
conn.commit
delete_user.close()
conn.close
This is a code block that should imo trigger the delete query, but nothing happens. Select query does indeed get the data.
UPDATE:
After some adjustments and passing list as a parameter fixed, the delete query now indeed works as intended.
get_user_id = conn.cursor()
get_user_id.execute('''
SELECT b.UserId
FROM Bindery b
INNER JOIN ActiveUser au
ON au.Id = b.UserId
WHERE au.UserId = ?
''', user_to_kick)
id_list = [id[0] for id in get_user_id.fetchall()]
placeholders = ", ".join(["?"] * len(id_list))
sql = 'DELETE FROM Bindery\
WHERE UserId in (%s)' % placeholders
delete_user = conn.cursor()
#delete from bindery first
delete_user.execute(sql, id_list)
conn.commit()
#delete from active user list
delete_user.execute('''
DELETE FROM ActiveUser
WHERE UserId = ?
''', user_to_kick)
conn.commit()
get_user_id.close()
delete_user.close()
conn.close()
I am trying to run a SQL "SELECT" query in Postgres from Python using Psycopg2. I am trying to compose the query string as below, but getting error message, using psycopg2 version 2.9.
from psycopg2 import sql
tablename = "mytab"
schema = "public"
query = sql.SQL("SELECT table_name from information_schema.tables where table_name = {tablename} and table_schema = {schema};")
query = query.format(tablename=sql.Identifier(tablename), schema=sql.Identifier(schema))
cursor.execute(query)
result = cursor.fetchone()[0]
Error:
psycopg2.error.InFailedSqlTransaction: current transaction is aborted, commands ignored until end of transaction block
Can someone please help. Thanks.
In the (a bit strange) query
select table_name
from information_schema.tables
where table_name = 'mytab'
and table_schema = 'public';
'mytab' and 'public' are literals, not identifiers. For comparison, mytab is an identifier here:
select *
from mytab;
Thus your format statement should look like this:
query = query.format(tablename=sql.Literal(tablename), schema=sql.Literal(schema))
Note that the quoted error message is somewhat misleading as it is about executing a query other than what is shown in the question.
Since this query is only dealing with dynamic values it can be simplified to:
import psycopg2
con = psycopg2.connect(<params>)
cursor = con.cursor()
tablename = "mytab"
schema = "public"
# Regular placeholders
query = """SELECT
table_name
from
information_schema.tables
where
table_name = %s and table_schema = %s"""
cursor.execute(query, [tablename, schema])
result = cursor.fetchone()[0]
# Named placeholders
query = """SELECT
table_name
from
information_schema.tables
where
table_name = %(table)s and table_schema = %(schema)s"""
cursor.execute(query, {"table": tablename, "schema": schema})
result = cursor.fetchone()[0]
my_connect = mysql.connector.connect(
host="localhost",
user="xyz",
passwd="xyz",
database="tracking"
)
my_conn = my_connect.cursor()
x = input("enter name")
query="SELECT * FROM trackingtable WHERE Customer_Name = \"x\"";
print(query)
my_conn.execute(query)
my_conn.close()
Query printed statement
How do i get the proper query using the input from user? I tried using placeholders but I couldn't get them to work
Try:
query = f"SELECT * FROM trackingtable WHERE Customer_Name = {x}"
It's an f-string in which you can plug in variables via {}.
If you need the "s inside the query:
query = f'SELECT * FROM trackingtable WHERE Customer_Name = "{x}"'
Do you need the ; at the end?
I am trying to get JSON rows from postgres using "psycopg2". value of records is like [ [{....},{...},{...}] ]. To get the correct JSON result ie. [{....},{...},{...}] i have to go for records1. Not sure why this is happening.
import psycopg2
import sys
import json
conn_string = "'host='localhost' dbname='postgres' user='postgres' password='password123'"
con=psycopg2.connect(conn_string)
cur = con.cursor()
cur.execute("select json_agg(art) from (select a.*, (select json_agg(b) from (select * from pfstklist where pfportfolioid = a.pfportfolioid ) as b) as pfstklist, (select json_agg(c) from (select * from pfmflist where pfportfolioid = a.pfportfolioid ) as c) as pfmflist from pfmaindetail as a) art")
records = cur.fetchall()
print(records) #This gives result [[{....},{...},{...}]]
records1=records[0]
print(records1) #This gives expected result [{....},{...},{...}]
cur.fetchall() gives you a list of records. You probably want cur.fetchone().
I have a list that contains the name of columns I want to retrieve from a table in the database.
My question is how to make the cursor select columns specified in the list. Do I have to convert nameList to a string variable before include it in the select statement? Thanks
nameList = ['A','B','C','D',...]
with sqlite3.connect(db_fileName) as conn:
cursor = conn.cursor()
cursor.execute("""
select * from table
""")
As long as you can be sure your input is sanitized -- to avoid SQL injection attack -- you can do:
...
qry = "select {} from table;"
qry.format( ','.join(nameList) )
cursor.execute(qry)
If you're on a really old version of Python do instead:
...
qry = "select %s from table;"
qry % ','.join(nameList)
cursor.execute(qry)
nameList = ["'A(pct)'",'B','C','D',...]
with sqlite3.connect(db_fileName) as conn:
cursor = conn.cursor()
cursor.execute("""
select {} from table
""".format(", ".join(nameList)))