简体   繁体   中英

How to store results from SQL query and use it?

I am trying to see whether the type is either a the letter "T" or between number 1-6 for the specific data entry found with name and password.

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

and then in psedocode i need something like:

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

I am using python 2.7

Here is a full script that will query the mysql DB, and use your above-mentioned logic to print the values. I've included the python code as well as the sample database code for this test case. Let me know if you have any questions.

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM