繁体   English   中英

如何从数据库中读取sqlite3中特定行?

[英]how do I read from a database for a specific row in sqlite3?

所以我试图建立一个非常简单的数据库,我使用的是sqlite3,而且我对使用python和其他东西进行编程非常陌生。 我的目标是能够输入一个名称,该名称是表中的一部分,并显示在其中找到该名称的行。我发现了一些教程,在该教程中,它们仅执行常规数据而不是动态搜索。 我没有太多示例要显示,但这是我正在工作的地方

import sqlite3

conn = sqlite3.connect('tutorial.db')

c = conn.cursor()

def create_table():
    c.execute("CREATE TABLE nameinfo(name TEXT, age REAL, color TEXT)")

def enter_dynamic_data():
    name = input("What\s their name? ")
    age = float(input("How old are they? "))
    color = input("What\'s their favorite color? ")

    c.execute("INSERT INTO nameinfo(name, age, color) VALUES (?, ?, ?)", (name, age, color))

conn.commit()

def read_from_database():
    sql = ("SELECT * FROM nameinfo")
    for row in c.execute(sql): #It names off the names that I can select from
        print(row[0])
        inp = input("Who would you like to know more about? ")
    for row in c.execute(sql): #Where I plan to have it only show a specific 
row, being the name age and favorite color of a person

        print(row)


read_from_database()

conn.close()

您可以使用SELECT * FROM nameinfo WHERE name = ? 完整的代码:

import sqlite3

conn = sqlite3.connect(':memory:')

c = conn.cursor()

def create_table():
    c.execute("CREATE TABLE nameinfo(name TEXT, age REAL, color TEXT)")

def enter_dynamic_data(name, age, color):
    c.execute("INSERT INTO nameinfo(name, age, color) VALUES (?, ?, ?)", (name, age, color))

create_table()
enter_dynamic_data("jack", 20, "green")
enter_dynamic_data("jill", 30, "red")
conn.commit()

def read_from_database():
    sql = "SELECT * FROM nameinfo"
    for row in c.execute(sql):  # It names off the names that I can select from
        print(row[0])
    name = "jack"
    sql = "SELECT * FROM nameinfo WHERE name = ?"
    for row in c.execute(sql, (name,)):
        print(row)

read_from_database()

conn.close()

暂无
暂无

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

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