使用 pyodbc 从数据库中检索特定值
Retreive specific value from DB with pyodbc
我正在尝试使用 Python 中的 pyodbc 从 SQL table 中获取特定值。
table dbo.passes 有 2 列:('user_name','password')
,值为 ('test','5555')
。
我有以下代码:
cursor.execute("SELECT password FROM [dbo].[passes] where user_name ='test'")
for row in cursor.fetchall():
print (row)
passw = input("enter pass ")
if passw == row:
print ("nice")
else:
print ("wrong")
如果我的输入是 5555
它与 "row" 不匹配,因为它是 ('5555 ')
在这种情况下,如何从数据库中只检索值 5555,而不是列表格式?
你不能。 SQL,按照设计,returns 个元组。访问 python 中的列表值,如下所示:
cursor.execute("SELECT password FROM [dbo].[passes] where user_name ='test'")
for row in cursor.fetchall():
print (row)
passw = input("enter pass ")
if passw == row['password']: # Could also be row[0], idk you have to try
print ("nice")
else:
print ("wrong")
第 [0] 行的建议有效,只是略有不同:
cursor.execute("SELECT RTRIM (password) FROM [dbo].[passes] where user_name = 'test'")
for row in cursor.fetchall():
print (row)
sqlpass = row[0]
print (sqlpass)
passw = input("enter pass ")
if passw == sqlpass:
print ("nice")
else:
print ("wrong")
RTRIM 是必需的,因为该字段是 varchar(20) 并且返回的字符串是存储的字符串加上任意数量的空格以达到 20 个字符。
How can I retrieve from the database only the value 5555 in this case, but not in a list format?
pyodbc 支持 .fetchval() 方法,即 returns 单个标量值:
count = cursor.execute('select count(*) from users').fetchval()
我正在尝试使用 Python 中的 pyodbc 从 SQL table 中获取特定值。
table dbo.passes 有 2 列:('user_name','password')
,值为 ('test','5555')
。
我有以下代码:
cursor.execute("SELECT password FROM [dbo].[passes] where user_name ='test'")
for row in cursor.fetchall():
print (row)
passw = input("enter pass ")
if passw == row:
print ("nice")
else:
print ("wrong")
如果我的输入是 5555
它与 "row" 不匹配,因为它是 ('5555 ')
在这种情况下,如何从数据库中只检索值 5555,而不是列表格式?
你不能。 SQL,按照设计,returns 个元组。访问 python 中的列表值,如下所示:
cursor.execute("SELECT password FROM [dbo].[passes] where user_name ='test'")
for row in cursor.fetchall():
print (row)
passw = input("enter pass ")
if passw == row['password']: # Could also be row[0], idk you have to try
print ("nice")
else:
print ("wrong")
第 [0] 行的建议有效,只是略有不同:
cursor.execute("SELECT RTRIM (password) FROM [dbo].[passes] where user_name = 'test'")
for row in cursor.fetchall():
print (row)
sqlpass = row[0]
print (sqlpass)
passw = input("enter pass ")
if passw == sqlpass:
print ("nice")
else:
print ("wrong")
RTRIM 是必需的,因为该字段是 varchar(20) 并且返回的字符串是存储的字符串加上任意数量的空格以达到 20 个字符。
How can I retrieve from the database only the value 5555 in this case, but not in a list format?
pyodbc 支持 .fetchval() 方法,即 returns 单个标量值:
count = cursor.execute('select count(*) from users').fetchval()