简体   繁体   中英

Search mutiple values from python dataframe in MS-SQL table

I have a string 'new_string' which contains a set of values to be searched in my MS-SQL table. I am getting an error " Could not parse rfc1738 URL from string ''2535488','2568394''"

new_string = "'2535488','2568394'"
cnxn = pyodbc.connect("DRIVER={SQL Server};SERVER=ABCDEF;DATABASE=my_db") #connection is successfully established.

data1 = pd.read_sql("""select * from my_table where my_col in (%s)""",new_string,cnxn)

But if I type the following query, I get my results.

data1 = pd.read_sql("""select * from my_table where my_col in ('2535488','2568394')""",cnxn)

How can I search for the values in my table?

You should use prepared statements like as follows:

In [58]: parms = ['2535488','2568394']

In [59]: q = """select * from my_table where my_col in ({})""".format(','.join(['?'] * len(parms)))

In [60]: q
Out[60]: 'select * from my_table where my_col in (?,?)'

now you should be able to do:

data1 = pd.read_sql(q, cnxn, params=parms)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM