SQLITE3 FROM表选择列WHERE布尔语句

时间:2018-05-06 09:26:16

标签: python sqlite

我尝试了3种不同的sqlite3语句来选择数据:

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

这些陈述的引用来自1 2。但是,它们都没有奏效。我怀疑我做的事情真的很傻但似乎无法解决这个问题。

我希望能够打印出用户名" monkey"的数据。感谢任何帮助,指出我的愚蠢错误。

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

1 个答案:

答案 0 :(得分:2)

您的表格定义的字段顺序为created_on, username, email,但您将数据插入created_on, email, username。因此,第一行的用户名为'monkey@gmail'

避免这种错误的一个好方法是在INSERT语句中指定列,而不是依赖于使原始表定义的顺序正确:

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