【问题标题】:How to store results from SQL query and use it?如何存储 SQL 查询的结果并使用它?
【发布时间】:2017-08-05 16:07:47
【问题描述】:

我正在尝试查看类型是字母“T”还是数字 1-6 之间的特定数据条目的名称和密码。

  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

【问题讨论】:

  • @py_noob 我正在使用 mysql,我正在尝试查看类型是否小于或等于值 5。

标签: python sql sqlcommand


【解决方案1】:

这是一个完整的脚本,它将查询 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');

【讨论】:

  • 不完全是,我不能调用 type = 'T' 因为它是 SQL 表的一部分,这就是我尝试运行 sql 命令的原因。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-11
  • 2017-12-15
  • 1970-01-01
  • 1970-01-01
  • 2012-05-18
  • 2012-06-12
  • 2022-07-26
相关资源
最近更新 更多