Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用不同的参数集在Python中使用多个参数执行存储过程_Python_Sql Server_Pyodbc - Fatal编程技术网

使用不同的参数集在Python中使用多个参数执行存储过程

使用不同的参数集在Python中使用多个参数执行存储过程,python,sql-server,pyodbc,Python,Sql Server,Pyodbc,我需要从Python中执行一个包含2个日期参数的存储过程。我想使用数据帧行中的参数集在循环中多次更改参数和执行过程。我的代码如下 def _get_dataset(date_param1, data_param2): sql="exec [dbo].[SP_Name] (%s,%s)" % (date_param1, date_param2) cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=xxx.xxx.x

我需要从Python中执行一个包含2个日期参数的存储过程。我想使用数据帧行中的参数集在循环中多次更改参数和执行过程。我的代码如下

def _get_dataset(date_param1, data_param2):
    sql="exec [dbo].[SP_Name] (%s,%s)" % (date_param1, 
    date_param2)
    cnxn = pyodbc.connect('DRIVER={SQL 
    Server};SERVER=xxx.xxx.xx.xx;DATABASE=db;UID=userid;PWD=password')
    cursor = cnxn.cursor()
    data = pd.read_sql(sql,cnxn)
    return data 

for i in range(len(dataframe)):
    first_date = df.iloc[i][0]
    second_date = df.iloc[i][1]
    _get_dataset(str(first), str(second))
我得到的错误

DatabaseError: Execution failed on sql 'exec [dbo].[SP_name] (2019-06-25,2019-06-24)': ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near '2019'. (102) (SQLExecDirectW)")

代码中有什么错误?提前谢谢

我没有SQL Server进行测试,但最好使用
read\u SQL
传递参数,因为它将使用底层数据库驱动程序以安全的方式执行字符串插值:

def _get_dataset(date_param1, data_param2):
    sql = "exec [dbo].[SP_Name] (?, ?)" 
    cnxn = pyodbc.connect(
       'DRIVER={SQL Server};SERVER=xxx.xxx.xx.xx;DATABASE=db;UID=userid;PWD=password'
    )
    cursor = cnxn.cursor()
    data = pd.read_sql(sql, cnxn, params=(date_param1, data_param2))
    return data 
您还可以使用类似SQLAlchemy的ORM来:


您尝试执行的实际查询是什么?请尝试在
sql
字符串:
“exec[dbo].[SP_Name]('%s','%s')上的日期前后加上单引号。”
-我身边没有MS SQLServer进行测试。@LajosArpad实际的查询应该类似于“exec SP_name”2019-06-24“2019-06-25”。@PauloScardine如果您直接在SQL Server中执行,而没有Python,它是否工作?我没有工作。这次我得到的错误如下;DatabaseError:在sql'exec[dbo].[SP_Name](?,?):('07002','[07002][Microsoft][ODBC sql Server驱动程序]计数字段不正确或语法错误(0)(SQLExecDirectW)')上执行失败。请查看数据库驱动程序文档,了解支持PEP 249的paramstyle中描述的五种语法样式中的哪一种。我不确定它是否是SQL Server的
%(名称)s
。另外,我不知道参数是什么类型的-如果它们是日期,您可能希望将它们转换为SQL Server能够理解的格式的字符串。要吗?在我今天的第一个任务之前,我有几分钟的时间来帮助您。谢谢@PauloScardine,但现在我无法进行缩放。请查看我关于使用SQLAlchemy消除数据库驱动程序之间差异的更新@古尔萨哈汗
In [559]: import sqlalchemy as sa

In [560]: pd.read_sql(sa.text('SELECT * FROM data where Col_1=:col1'), 
   .....:             engine, params={'col1': 'X'})
   .....: 
Out[560]: 
   index  id                        Date Col_1  Col_2  Col_3
   0      0  26  2010-10-18 00:00:00.000000     X   27.5      1