简体   繁体   中英

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] )

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. 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,)]. Logically you can use the fetchone() as you only want one username. 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()

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