簡體   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