简体   繁体   中英

SQLITE3 FROM table Select column WHERE Boolean statement

I have tried 3 different variations of sqlite3 statement to SELECT a data:

    cursor.execute('SELECT * FROM users WHERE username = ?', (username,))
    cursor.execute('''SELECT * FROM users WHERE username = ?;''', (username,))
    cursor.execute('SELECT * FROM users WHERE username = "monkey1" ')

References for these statements are from 1 2 . However, none of them worked. I suspect that I am doing something really silly but can't seem to figure this out.

I want to be able to print out the data of username "monkey". Appreciate any help to point out my silly mistake.

import sqlite3
import datetime


def get_user(connection, rows='all', username=None ):
    """Function to obtain data."""
    #create cursor object from sqlite connection object
    cursor = connection.cursor() 
    if rows == 'all':
        print("\nrows == 'all'")
        cursor.execute("SELECT * FROM users")
        data = cursor.fetchall()
        for row in data:
            print(row)

    if rows == 'one':
        print("\nrows == 'one'")
        cursor.execute('SELECT * FROM users WHERE username = ?', (username,))
        #cursor.execute('''SELECT * FROM users WHERE username = ?;''', (username,))
        #cursor.execute('SELECT * FROM users WHERE username = "monkey1" ')
        data = cursor.fetchone()
        print('data = ',data)

    cursor.close()
    return data



def main():
    database = ":memory:"

    table = """ CREATE TABLE IF NOT EXISTS users (
                    created_on  TEXT    NOT NULL UNIQUE,
                    username    TEXT    NOT NULL UNIQUE,
                    email       TEXT    NOT NULL UNIQUE
                 ); """

    created_on = datetime.datetime.now()
    username   = 'monkey'
    email      = 'monkey@gmail'

    created_on1 = datetime.datetime.now()
    username1   = 'monkey1'
    email1      = 'monkey1@gmail'

    # create a database connection & cursor
    conn = sqlite3.connect(database)
    cursor = conn.cursor() 

    # Insert data
    if conn is not None:
        # create user table
        cursor.execute(table)
        cursor.execute('INSERT INTO users VALUES(?,?,?)',(
            created_on, email, username))
        cursor.execute('INSERT INTO users VALUES(?,?,?)',(
            created_on1, email1, username1))
        conn.commit()
        cursor.close()
    else:
        print("Error! cannot create the database connection.")

    # Select data
    alldata = get_user(conn, rows='all')
    userdata = get_user(conn, rows='one', username=username )
    print('\nalldata = ', alldata)
    print('\nuserdata = ', userdata)
    conn.close()


main()

Your table definition has the fields in order created_on, username, email but you inserted your data as created_on, email, username . Therefore the username of the first row was 'monkey@gmail' .

A good way to avoid this kind of mistake is to specify the columns in the INSERT statement rather than relying on getting the order of the original table definition correct:

INSERT INTO users (created_on, email, username) VALUES (?,?,?)

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