简体   繁体   English

如何使用Python搜索(或选择)SQLite3中选定列的所有行?

[英]How to search (or select) all rows in selected column in SQLite3 with Python?

I am trying to find out how to search (or select) all rows in a column, regardless of whether I know the length of the column or not. 我试图找出如何搜索(或选择)列中的所有行,而不管我是否知道列的长度。

I am testing out how things work with SQLite and while trying to do a simple inclusion check (seeing if a user entered bit of information is already contained within a specific column in the database) I noticed that no matter what I typed into the row[] command I always got back only the entry from the first row (as if I'd used row[0] ) 我正在测试SQLite的工作方式,并尝试进行简单的包含检查(查看用户输入的信息是否已包含在数据库的特定列中),我注意到无论我row[]键入什么内容row[]命令,我总是只从第一行取回条目(就像我使用了row[0]

here is my bit of code: 这是我的一些代码:

import sqlite3
conn = sqlike3.connect("testDb.DB")
c = conn.cursor()

def createUsr():
    global usrName_
    usrName_ = input('Enter your desired username: ')
    usrName_Search = c.execute('SELECT usrName from usrInfo')
    for row in usrName_Search:
        if usrName_ in row[]:
            print('Username taken')
            createUsr()
        else:
            print('username created')
            c.execute('INSERT INTO usrInfo VALUE ?', (usrName_,))

createUsr()

This is a shortened version of the actual code (the other one had more values, but this was the bit that was erroring so I decided to focus on this) 这是实际代码的简化版本(另一个具有更多值,但这是有误的地方,所以我决定专注于此)

I don't know what I need to enter into row[] to select every entry, or if there is another way I should be going about doing this. 我不知道我需要输入row[]来选择每个条目,还是不知道我应该采取其他方式进行此操作。 Any help would be greatly appreciated 任何帮助将不胜感激

You have to actually select the search results and iterate over them. 您必须实际选择搜索结果并对其进行迭代。 conn.cursor.fetchall() will return the results in a list of tuples like [(usrName1,),(usrName2,)]. conn.cursor.fetchall()将在[[usrName1,),(usrName2,)]之类的元组列表中返回结果。 Logically you can use the fetchone() as you only want one username. 从逻辑上讲,您可以使用fetchone(),因为您只需要一个用户名。 Therefore, I would do the following: 因此,我将执行以下操作:

import sqlite3
conn = sqlike3.connect("testDb.DB")
c = conn.cursor()

def createUsr():
    global usrName_
    usrName_ = input('Enter your desired username: ')
    sql = """SELECT usrName FROM usrInfo WHERE usrName = ?"""
    usrName_Search = c.execute(sql, (usrName_,)).fetchone()
    if not usrName_Search:  #same as if usrName_Search ==None
        print('username created')
        sql = """INSERT INTO usrInfo (usrName) VALUES (?)"""
        c.execute(sql, (usrName_,))
    else:
        print('Username taken')
        createUsr()

createUsr()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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