我是Python的新手。尽管这与我之前提出的问题类似,但我现在正在寻找一些专门针对语法的信息。我在下面设置了以下测试,以尝试从一个查询中提取一个数字并将其输入另一个查询中。我遇到的特定问题是“ cursor.execute(“从提要WHERE id =” + str(rows))中选择文本“行。我收到语法错误。
当我使用Python打印查询时,该记录会在括号中显示,并在其后带有一个逗号,我认为这是导致错误的原因(因为这些字符对于下一个查询而言是意外的)。
对此,我的问题是,我应该使用“替换”将结果分解为没有其他字符的数字,还是应该做些不同的事情。传递此号码的正确方法是什么?
import psycopg2
try:
connect_str = "dbname='mydatabase' user='myuser' host='localhost' " + \
"password='mypassword'"
# establish a connection
conn = psycopg2.connect(connect_str)
# cursor to execute queries
cursor = conn.cursor()
# run am initial SELECT statement
cursor.execute("SELECT result FROM mytable WHERE id=1")
# assign fetched data to a variable named rows
rows = cursor.fetchone()
# for testing purposes, print the variable
print(rows)
# for testing purposes, use it in a sentence
print("the following is your next row",rows)
# feed the result stored in rows into another query
cursor.execute("SELECT result FROM mytable WHERE id=" + str(rows))
morerows = cursor.fetchone()
except Exception as e:
print("cant connect")
print(e)
答案 0 :(得分:1)
cursor
类具有非常有用的方法mogrify()
,可用于查看查询的构造方式。您可以尝试使用它进行查询,然后将mogrify
替换为execute
以运行查询。
您应该仔细阅读文档中的Passing parameters to SQL queries。
一些例子:
# pass an integer constant:
print(cursor.mogrify("SELECT result FROM mytable WHERE id= %s", (111, )))
# pass two variables:
a_number = 222
a_string = 'string'
print(cursor.mogrify("SELECT result FROM mytable WHERE id= %s or str = %s", (a_number, a_string)))
#pass a tuple:
args = (333, 'another_string')
print(cursor.mogrify("SELECT result FROM mytable WHERE id= %s or str = %s", args))
上面的代码给出输出:
b'SELECT result FROM mytable WHERE id= 111'
b"SELECT result FROM mytable WHERE id= 222 or str = 'string'"
b"SELECT result FROM mytable WHERE id= 333 or str = 'another_string'"