gpt4 book ai didi

python - pyodbc变量查询

转载 作者:行者123 更新时间:2023-12-05 07:29:19 25 4
gpt4 key购买 nike

我正在尝试使用变量进行查询,但字符串变量不起作用。我应该如何格式化查询中的变量 PrimaryAxisSecondaryAxis?我使用了来自 https://github.com/mkleehammer/pyodbc/wiki/Getting-started#parameters 的引用资料在页面上使用单引号。我没有运气就尝试了单引号和双引号。

import pyodbc

# Connect to database
conn_str = (
r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};'
r'DBQ=C:\Temp\TestDB.accdb;'
r'Uid=;'
r'Pwd=;'
)

# Make cursor
connection = pyodbc.connect(conn_str)
connection.setencoding('utf-8')
cursor = connection.cursor()

# Create test table
cursor.execute("CREATE TABLE Coordinates (ID integer, X integer, Y integer)")
connection.commit()

# Create test data (Error "Missing semicolon (;)" if multiple values in one insert, thats why multiple insertions... not the main question)
cursor.execute("INSERT INTO Coordinates (ID, X, Y) VALUES (1,10,10);")
cursor.execute("INSERT INTO Coordinates (ID, X, Y) VALUES (2,20,10);")
cursor.execute("INSERT INTO Coordinates (ID, X, Y) VALUES (3,30,10);")
connection.commit()

# Filter parameters
Line = 10
Start = 10
End = 30

# Works
cursor.execute(r"""
SELECT *
FROM Coordinates
WHERE Y = ? AND X BETWEEN ? AND ? """, Line, Start, End )

rows = cursor.fetchall()
for row in rows:
print(row)

# does not work - main question
PrimaryAxis = 'X'
SecondaryAxis = 'Y'

cursor.execute(r"""
SELECT *
FROM Coordinates
WHERE ? = ? AND ? BETWEEN ? AND ? """, SecondaryAxis, Line, PrimaryAxis, Start, End )

rows = cursor.fetchall()
for row in rows:
print(row)

最佳答案

您可以简单地使用数据库占位符:

# Filter parameters
line = 10
start = 10
end = 30
primary_axis = "X"
secondary_axis = "Y"
query = """
SELECT *
FROM Coordinates
WHERE ? = ? AND ? BETWEEN ? AND ?
"""
cursor.execute(query, (secondary_axis, line, primary_axis, start, end))
...

关于python - pyodbc变量查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52843757/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com