python - pyodbc execute variable becomes @P1
问题描述
Hi I'm doing something like:
# pyodbc extension
cursor.execute("select a from tbl where b=? and c=?", x, y)
-- some values in the query in provided by variables. But sometimes the variable is interpreted as @P1
in the query.
For example:
import pyodbc
ch = pyodbc.connect('DRIVER={SQL Server};SERVER=xxxx;DATABASE=xxx;Trusted_Connection=True')
cur = ch.cursor()
x = 123
cur.execute('''
CREATE TABLE table_? (
id int IDENTITY(1,1) PRIMARY KEY,
obj varchar(max) NOT NULL
)
''', x).commit()
This results in a new table named table_@P1
(I want table_123
)
Another example:
x = 123
cur.execute('''
CREATE TABLE table_2 (
id int IDENTITY(1,1) PRIMARY KEY,
obj varchar(?) NOT NULL
)
''', x).commit()
it reports error:
ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near '@P1'. (102) (SQLExecDirectW)")
Again, the variable is interpreted as @P1
.
Anyone know how to fix this? Any help's appreciated. Thanks-
解决方案
In your first case, parameter substitution does not work for table/column names. This is common to the vast majority of (if not all) database platforms.
In your second case, SQL Server does not appear to support parameter substitution for DDL statements. The SQL Server ODBC driver converts the pyodbc parameter placeholders (?
) to T-SQL parameter placeholders (@P1
, @P2
, ...) so the statement passed to SQL Server is
CREATE TABLE table_2 (id int IDENTITY(1,1) PRIMARY KEY, obj varchar(@P1) NOT NULL
specifically
exec sp_prepexec @p1 output,N'@P1 int',N'CREATE TABLE table_2 (id int IDENTITY(1,1) PRIMARY KEY, obj varchar(@P1) NOT NULL',123
and when SQL Server tries to prepare that statement it expects a literal value, not a parameter placeholder.
So, in both cases you will need to use dynamic SQL (string formatting) to insert the appropriate values.
推荐阅读
- python - 如何在 kivy 中的形状之间添加填充?
- android-10.0 - Android Q Edge to Edge 应用内容不显示透明导航栏
- java - restTemplate.getForObject 上的 HttpClientErrorException
- c# - 如何在 C# 中压缩我的世界块?
- oracle - 带有Oracle的PHP PDO,当输出参数是游标时调用存储过程
- php - Laravel:不允许序列化 'Illuminate\Http\UploadedFile'
- django - DatabaseError:无法在 django 上打开数据库文件
- cypress - 如何在测试运行之前存根在 html 上定义的变量
- pentaho - pentaho spoon: how to get filename as value?
- python - How to create dataframe of output