簡體   English   中英

使用pyodbc從DB中檢索特定值

[英]Retreive specific value from DB with pyodbc

我試圖從Python中的pyodbc獲取SQL表中的特定值。 表dbo.passes有兩列:( ('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它與“行”不匹配,因為它出現為('5555 ')

在這種情況下,如何從數據庫中僅檢索值5555,而不是以列表格式檢索?

你不能。 SQL,按設計,返回元組。 在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個字符。

在這種情況下,如何從數據庫中僅檢索值5555,而不是以列表格式檢索?

pyodbc支持返回單個標量值的.fetchval()方法:

count = cursor.execute('select count(*) from users').fetchval()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM