SQLITE3从表Select列中选择布尔语句

2024-10-04 03:23:50 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

这些语句的引用来自12。但是,没有一个有效。我怀疑我在做一件非常愚蠢的事,但似乎无法弄明白这一点。你知道吗

我想能够打印出用户名“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()

Tags: fromexecutedatadatetimeusernameconnectionconnwhere
1条回答
网友
1楼 · 发布于 2024-10-04 03:23:50

表定义中的字段按created_on, username, email的顺序排列,但插入的数据是created_on, email, username。因此,第一行的用户名是'monkey@gmail'。你知道吗

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

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

相关问题 更多 >