db = sqlite3.connect("database.db") # 连接到一个现有的数据库,如果没有这个文件就创建它
cur = db.cursor() # 创建一个cursor,才能执行SQL语句
# cur.execute(你想执行的SQL语句) cur.execute("CREATE TABLE books ('title' TEXT NOT NULL, 'price' REAL, 'sales' INTEGER, 'category' TEXT);") # 创建一个表
res = cur.execute("SELECT name FROM sqlite_master") # SQLite内置了一个名叫“sqlite_master”的表,储存了所有已创建的表
print(res.fetchone()) # 输出('books',)
cur.execute(""" INSERT INTO books VALUES ('The Great Gatsby', 50.99, 4, 'Fiction'), ('The Lord of the Rings', 55.99, 3, 'Fantasy') """) db.commit() # 插入两名学生 # 会自动地创建事务,无需手动加上“BEGIN TRANSACTION” # 需要手动db.commit()
category = input("category:") res = cur.execute("SELECT title FROM books WHERE category = ?", (category, )) # 注意传入的第二个参数是一个元组,不能直接传category # 请使用“?”占位符,不要使用 f"SELECT title FROM books WHERE category = {category}"或者其他任何方式 # 否则可能会受到SQL注入攻击(SQL injection attacks) # “?”占位符会自动处理传入的字符串,防止SQL注入
res = cur.execute('SELECT title, price FROM books') for row in res: print(row) ''' 输出 ('The Great Gatsby', 50.99) ('The Lord of the Rings', 55.99) ('To Kill a Mockingbird', 25.99) ('Pride and Prejudice', 40.99) ('To Kill a Mockingbird', 25.99) ('Pride and Prejudice', 40.99) ('1984', 35.99) ('The Catcher in the Rye', 60.99) ('Animal Farm', 30.5) ('The Hobbit', 45.0) '''