2017-08-05 96 views
0

我想看看是否類型是字母「T」或數字1-6之間的具體數據輸入名稱和密碼找到。如何存儲來自SQL查詢的結果並使用它?

sql = 'SELECT type FROM table name WHERE name = "{}" AND password = "{}"'.format(username, password) 

,然後在psedocode我需要的東西,如:

if type =< 5: 
     int() 
elif type = "T" 
     string() 

我使用Python 2.7

+0

@py_noob我使用的MySQL,我想看看類型是小於或等於值5 – Eli

回答

0

這是一個完整的腳本,將查詢MySQL數據庫,並使用上述邏輯來打印值。我已經包含了python代碼以及這個測試用例的示例數據庫代碼。如果您有任何問題,請告訴我。

的Python

import pymysql 

connection = pymysql.connect(user='username', passwd='password', 
           host='localhost', 
           database='database') 

cursor = connection.cursor() 

NAME = 'Person_A' 
PASSWORD = 'Password_A' 
query = ("SELECT * FROM My_TABLE WHERE NAME = '%(1)s' AND PASSWORD = '%(2)s';" % {"1" : NAME, "2" : PASSWORD}) 


cursor.execute(query) 

for item in cursor: 

    type = item[0] 

    if type.isdigit(): 
     if int(type) <6: 
      print('Type is a number less than 6') 
     else: 
      print('Type is a number but not less than 6') 
    else: 
     if type == 'T': 
      print('Type is a string == T') 
     else: 
      print('Type is a string but not the letter T') 

MYSQL

CREATE TABLE MY_TABLE (TYPE VARCHAR(255), NAME VARCHAR(255), PASSWORD VARCHAR(255)); 

INSERT INTO MY_TABLE VALUES ('T','Person_A','Password_A'),('4','Person_A','Password_A'),('7','Person_B','Password_B'),('t','Person_C','Password_C'); 
+0

不相當,我不能調用type ='T',因爲它是SQL表的一部分,這就是爲什麼我要運行sql命令。 – Eli

+0

@Eli已更新,請使用上述內容 –

相關問題