Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to insert variables in read_sql_query using python

Tags:

python

sqlite

I am trying to retrieve data from sqlite3 with the help of variables. It is working fine with execute() statement but i would like to retrieve columns also and for that purpose i am using read_sql_query() but i am unable to pass variables in read_sql_query(), please follow below code:

def cal():
  tab = ['LCOLOutput']
  column_name = 'CUSTOMER_EMAIL_ID'
  xyz = '**[email protected]'
  for index, m in enumerate(tab):
      table_name = m
      sq = "SELECT * FROM ? where ?=?;" , (table_name, column_name, xyz,)
      df = pandas.read_sql_query(sq,conn)
      writer = 
      pandas.ExcelWriter('D:\pandas_simple.xlsx',engine='xlsxwriter')
      df.to_excel(writer, sheet_name='Sheet1')
      writer.save()
like image 281
Fasih Ahmed Avatar asked Jun 18 '26 11:06

Fasih Ahmed


1 Answers

You need to change the syntax with the method read_sql_query() from pandas, check the doc.

For sqlite, it should work with :

sq = "SELECT * FROM ? where ?=?;" 
param = (table_name, column_name, xyz,)
df = pandas.read_sql_query(sq,conn, params=param)

EDIT : otherwise try with the following formatting for the table :

sq = "SELECT * FROM {} where ?=?;".format(table_name)
param = (column_name, xyz,)
df = pandas.read_sql_query(sq,conn, params=param)

Check this answer explaining why table cannot be passed as parameter directly.

like image 115
PRMoureu Avatar answered Jun 20 '26 00:06

PRMoureu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!