python 读写sqlite3

import sqlite3

# 连接到SQLite3数据库
conn = sqlite3.connect('example.db')

# 创建一个表
conn.execute('''CREATE TABLE IF NOT EXISTS users
             (id INTEGER PRIMARY KEY AUTOINCREMENT,
             name TEXT NOT NULL,
             age INTEGER NOT NULL);''')

# 插入一些数据
conn.execute("INSERT INTO users (name, age) VALUES (?, ?)", ('Alice', 30))
conn.execute("INSERT INTO users (name, age) VALUES (?, ?)", ('Bob', 25))
conn.execute("INSERT INTO users (name, age) VALUES (?, ?)", ('Charlie', 35))
conn.commit()

# 查询所有行并打印结果
cursor = conn.execute("SELECT id, name, age FROM users")
for row in cursor:
    print(f"id: {row[0]}, name: {row[1]}, age: {row[2]}")

# 关闭数据库连接
conn.close()

 

posted @ 2023-04-28 19:55  myrj  阅读(18)  评论(0编辑  收藏  举报