所以我试图创建一个非常简单的数据库,我正在使用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()
答案 0 :(得分:1)
您可以使用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()