Python Forum
pass captured value from input() to where clause
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
pass captured value from input() to where clause
#1
How can pass the value captured in a variable using input() to a where clause in a select statement?

def ada():
    import pyodbc
    import pandas as pd
    conn = pyodbc.connect('Driver={ODBC Driver 17 for SQL Server};'
                          'Server=ABCD400;'
                          'Database=TestDb;'
                          'Trusted_Connection=yes;')
    SQL_Query = pd.read_sql_query('''select distinct DoctorName,Department from [TestDb].[dbo].[EveryDayAvailability] ''', conn)
    df = pd.DataFrame(SQL_Query, columns=['DoctorName','Department'])
    print (df)
    DName = input("Please provide the name of the Doctor you would like to visit ?")
    print("Printed below are the list of appointments for this doctor ")
    SQL_Query = pd.read_sql_query('''select DoctorName,0900 from [TestDb].[dbo].[EveryDayAvailability where DoctorName=DName] ''', conn)
    df = pd.DataFrame(SQL_Query, columns=['DoctorName','0900'])
    print (df)
Reply
#2
Replace line 14 with
SQL_Query = pd.read_sql_query('''select DoctorName,0900 from [TestDb].[dbo].[EveryDayAvailability where DoctorName={}] '''.format(DName), conn)
Reply
#3
No, one should never be writing queries by essentially joining strings as that's vulnerable to SQL injection. It looks like read_sql_query takes an argument, params that's used for passing parameters to the query (see the docs), so you should be using that.
Reply
#4
(Sep-06-2019, 06:40 PM)micseydel Wrote: Replace line 14 with
SQL_Query = pd.read_sql_query('''select DoctorName,0900 from [TestDb].[dbo].[EveryDayAvailability where DoctorName={}] '''.format(DName), conn)

It still gives me an error:
>>> def ada():
... import pyodbc
... import pandas as pd
... conn = pyodbc.connect('Driver={ODBC Driver 17 for SQL Server};'
... 'Server=usmlvv1sql400;'
... 'Database=TestDb;'
... 'Trusted_Connection=yes;')
... SQL_Query = pd.read_sql_query('''select distinct DoctorName,Department from [TestDb].[dbo].[EveryDayAvailability] ''', conn)
... df = pd.DataFrame(SQL_Query, columns=['DoctorName','Department'])
... print (df)
... DName = input("Please provide the name of the Doctor you would like to visit ?")
... print("Printed below are the list of appointments for this doctor ")
... SQL_Query = pd.read_sql_query('''select DoctorName,0900 from [TestDb].[dbo].[EveryDayAvailability where DoctorName={}] '''.format(DName), conn)
... df = pd.DataFrame(SQL_Query, columns=['DoctorName','0900'])
... print (df)
...
>>> ada()
DoctorName Department
0 John Nephrology
1 Sharon ENT
2 Steve Cardiology
Please provide the name of the Doctor you would like to visit ?John
Printed below are the list of appointments for this doctor
Traceback (most recent call last):
File "C:\Users\A\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\sql.py", line 1431, in execute
cur.execute(*args)
pyodbc.ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name 'TestDb.dbo.EveryDayAvailability where DoctorName='John''. (208) (SQLExecDirectW)")

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 13, in ada
File "C:\Users\A\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\sql.py", line 314, in read_sql_query
parse_dates=parse_dates, chunksize=chunksize)
File "C:\Users\A\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\sql.py", line 1468, in read_query
cursor = self.execute(*args)
File "C:\Users\A\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\sql.py", line 1445, in execute
raise_with_traceback(ex)
File "C:\Users\A\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\compat\__init__.py", line 420, in raise_with_traceback
raise exc.with_traceback(traceback)
File "C:\Users\A\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\sql.py", line 1431, in execute
cur.execute(*args)
pandas.io.sql.DatabaseError: Execution failed on sql 'select DoctorName,0900 from [TestDb].[dbo].[EveryDayAvailability where DoctorName='John'] ': ('42S02', "[42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name 'TestDb.dbo.EveryDayAvailability where DoctorName='John''. (208) (SQLExecDirectW)")
Reply
#5
It's because it needs quotes, but as ndc85430 what I suggested is a bad (terrible) practice. Find an ORM or some library that does this kind of thing for you. (I would recommend one if I could, but I'd have to do research that you could just do yourself.)
Reply
#6
where do I need the quotes?
I still can't get it.Can you please be precise
Thanks

updated code:

def ada():
import pyodbc
import pandas as pd
conn = pyodbc.connect('Driver={ODBC Driver 17 for SQL Server};'
'Server=ABCD400;'
'Database=TestDb;'
'Trusted_Connection=yes;')
global DName
SQL_Query = pd.read_sql_query("select distinct DoctorName,Department from [TestDb].[dbo].[EveryDayAvailability] ", conn)
df = pd.DataFrame(SQL_Query, columns=['DoctorName','Department'])
print (df)
print("Printed is the list of Doctors by department ")
DName = input("Please provide the name of the Doctor you would like to visit ?")
SQL_Query = pd.read_sql_query("select DoctorName,0900 from [TestDb].[dbo].[EveryDayAvailability] where DoctorName={}".format("DName"), conn)
DoctorName=DName
df = pd.DataFrame(SQL_Query, columns=['DoctorName','0900'])
print (df)

>>> ada()
DoctorName Department
0 John Nephrology
1 Sharon ENT
2 Steve Cardiology
Printed is the list of Doctors by department
Please provide the name of the Doctor you would like to visit ?John
Traceback (most recent call last):
File "C:\Users\ABC123\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\sql.py", line 1431, in execute
cur.execute(*args)
pyodbc.ProgrammingError: ('42S22', "[42S22] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name 'DName'. (207) (SQLExecDirectW)")

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 14, in ada
File "C:\Users\ABC123\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\sql.py", line 314, in read_sql_query
parse_dates=parse_dates, chunksize=chunksize)
File "C:\Users\ABC123\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\sql.py", line 1468, in read_query
cursor = self.execute(*args)
File "C:\Users\ABC123\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\sql.py", line 1445, in execute
raise_with_traceback(ex)
File "C:\Users\ABC123\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\compat\__init__.py", line 420, in raise_with_traceback
raise exc.with_traceback(traceback)
File "C:\Users\ABC123\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\sql.py", line 1431, in execute
cur.execute(*args)
pandas.io.sql.DatabaseError: Execution failed on sql 'select DoctorName,0900 from [TestDb].[dbo].[EveryDayAvailability] where DoctorName=DName': ('42S22', "[42S22] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name 'DName'. (207) (SQLExecDirectW)")

>>> def ada():
... import pyodbc
... import pandas as pd
... conn = pyodbc.connect('Driver={ODBC Driver 17 for SQL Server};'
... 'Server=ABCD400;'
... 'Database=TestDb;'
... 'Trusted_Connection=yes;')
... global DName
... SQL_Query = pd.read_sql_query("select distinct DoctorName,Department from [TestDb].[dbo].[EveryDayAvailability] ", conn)
... df = pd.DataFrame(SQL_Query, columns=['DoctorName','Department'])
... print (df)
... print("Printed is the list of Doctors by department ")
... DName = input("Please provide the name of the Doctor you would like to visit ?")
... SQL_Query = pd.read_sql_query("select DoctorName,0900 from [TestDb].[dbo].[EveryDayAvailability] where DoctorName=s%" %(DName), conn)
... df = pd.DataFrame(SQL_Query, columns=['DoctorName','0900'])
... print (df)
...
>>> ada()
DoctorName Department
0 John Nephrology
1 Sharon ENT
2 Steve Cardiology
Printed is the list of Doctors by department
Please provide the name of the Doctor you would like to visit ?John
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 14, in ada
ValueError: incomplete format
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to pass encrypted pass to pyodbc script tester_V 0 853 Jul-27-2023, 12:40 AM
Last Post: tester_V
  How to use the LIKE clause in Python Columbo 9 1,620 Oct-09-2022, 10:22 PM
Last Post: Larz60+
  SQL Query is not executing WHERE clause hammer 7 2,323 Nov-15-2021, 01:44 PM
Last Post: hammer
  How does this if clause work? Pedroski55 3 2,266 Jun-10-2021, 06:31 AM
Last Post: Gribouillis
  Pass by object reference when does it behave like pass by value or reference? mczarnek 2 2,552 Sep-07-2020, 08:02 AM
Last Post: perfringo
  can i raise an exception in a try clause? Skaperen 14 5,721 Dec-19-2019, 12:29 AM
Last Post: Skaperen
  Pass by reference vs Pass by value leodavinci1990 1 2,198 Nov-20-2019, 02:05 AM
Last Post: jefsummers
  why does my python request cannot work with proxy and cannot get captured by fiddler szhangpy 0 2,005 Jun-27-2019, 10:48 PM
Last Post: szhangpy
  finally clause Skaperen 6 3,873 Jun-02-2019, 09:02 PM
Last Post: snippsat
  unable to pass a input after changing the user from root to non root using python avinash 3 3,178 Apr-08-2019, 10:05 AM
Last Post: avinash

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020