从MS-SQL表中的python数据帧中搜索多个值

时间:2018-04-12 10:14:02

标签: python sql sql-server pandas dataframe

我有一个字符串' new_string'其中包含一组要在MS-SQL表中搜索的值。我收到错误" 无法解析rfc1738网址来自字符串' 2535488',' 2568394''&# 34;

this.SetCurrentValue(DocProperty, newValue);

但如果我输入以下查询,我会得到我的结果。

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)

如何搜索表格中的值?

1 个答案:

答案 0 :(得分:0)

您应该使用如下准备语句:

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 (?,?)'

现在你应该可以做到:

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