Python的SQLite和Tkinter库来创建一个具有增删改查(CRUD)功能的系统插入(Create)、读取(Retrieve)、更新(Update)和删除(Delete)

要使用Python的SQLite和Tkinter库来创建一个具有增删改查(CRUD)功能的系统,你可以编写更复杂的逻辑来处理插入(Create)、读取(Retrieve)、更新(Update)和删除(Delete)操作。下面是一个扩展的示例代码,展示如何结合Tkinter和SQLite实现这些功能:

python
复制
import sqlite3
import tkinter as tk
from tkinter import messagebox

# 连接SQLite数据库
def connect_db():
    conn = sqlite3.connect('example.db')
    return conn

# 执行查询并返回结果
def execute_query(conn, query, params=()):
    cursor = conn.cursor()
    cursor.execute(query, params)
    if query.lower().startswith('select'):
        return cursor.fetchall()
    else:
        conn.commit()
        return cursor.rowcount

# 显示查询结果
def show_results(results):
    text_widget.delete('1.0', tk.END)
    for row in results:
        text_widget.insert(tk.END, str(row) + '\n')

# 创建数据表(如果尚未存在)
def create_table():
    conn = connect_db()
    cursor = conn.cursor()
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS users (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL,
            age INTEGER
        )
    ''')
    conn.close()

# 插入数据
def insert_data():
    name = name_entry.get()
    age = age_entry.get()
    if not name or not age:
        messagebox.showerror("错误", "请输入完整的信息!")
        return
    query = "INSERT INTO users (name, age) VALUES (?, ?)"
    conn = connect_db()
    try:
        row_count = execute_query(conn, query, (name, int(age)))
        messagebox.showinfo("成功", f"插入了 {row_count} 行数据。")
    except Exception as e:
        messagebox.showerror("错误", str(e))
    finally:
        conn.close()

# 更新数据
def update_data():
    id_ = id_entry.get()
    name = name_entry.get()
    age = age_entry.get()
    if not id_ or not name or not age:
        messagebox.showerror("错误", "请输入完整的信息!")
        return
    query = "UPDATE users SET name=?, age=? WHERE id=?"
    conn = connect_db()
    try:
        row_count = execute_query(conn, query, (name, int(age), int(id_)))
        messagebox.showinfo("成功", f"更新了 {row_count} 行数据。")
    except Exception as e:
        messagebox.showerror("错误", str(e))
    finally:
        conn.close()

# 删除数据
def delete_data():
    id_ = id_entry.get()
    if not id_:
        messagebox.showerror("错误", "请输入要删除的数据的ID!")
        return
    query = "DELETE FROM users WHERE id=?"
    conn = connect_db()
    try:
        row_count = execute_query(conn, query, (int(id_),))
        messagebox.showinfo("成功", f"删除了 {row_count} 行数据。")
    except Exception as e:
        messagebox.showerror("错误", str(e))
    finally:
        conn.close()

# 查询数据
def query_data():
    query = "SELECT * FROM users"
    conn = connect_db()
    try:
        results = execute_query(conn, query)
        show_results(results)
    except Exception as e:
        messagebox.showerror("错误", str(e))
    finally:
        conn.close()

# 创建Tkinter窗口
root = tk.Tk()
root.title("SQLite CRUD 系统")

# 创建插入数据的表单
name_label = tk.Label(root, text="Name:")
name_label.pack(side=tk.LEFT)
name_entry = tk.Entry(root)
name_entry.pack(side=tk.LEFT)

age_label = tk.Label(root, text="Age:")
age_label.pack(side=tk.LEFT)
age_entry = tk.Entry(root)
age_entry.pack(side=tk.LEFT)

insert_button = tk.Button(root, text="插入", command=insert_data)
insert_button.pack(side=tk.LEFT)

# 创建更新数据的表单
id_label = tk.Label(root, text="ID:")
id_label.pack(side=tk.LEFT)
id_entry = tk.Entry(root)
id_entry.pack(side=tk.LEFT)

update_button = tk.Button(root, text="更新", command=update_data)
update_button.pack(side=tk.LEFT)

# 创建删除数据的表单
delete_button = tk.Button(root, text="删除", command=delete_data)
delete_button.pack(side=tk.LEFT)

# 创建查询数据的表单
query_button = tk.Button(root, text="查询", command=query_data)
query_button.pack(side=tk.LEFT)

# 创建显示结果的文本框
text_widget = tk.Text(root, height=10, width=50)
text_widget.pack(pady=10)

# 创建数据表
create_table()

# 运行Tkinter事件循环
root.mainloop()


在这个示例中,我们创建了一个具有多个按钮和文本框的Tkinter窗口,用于插入、更新、删除和查询用户数据。每个按钮都绑定了一个回调函数,用于执行相应的数据库操作。我们还添加了一个文本框用于显示查询结果。

请注意,这个示例假设你已经有了一个名为example.db的SQLite数据库,并且该数据库中有一个名为users的表。如果表不存在,create_table函数会在第一次运行时创建它。

在实际应用中,你可能还需要添加更多的错误处理逻辑、输入验证以及更友好的用户界面。此外,对于大型应用程序,你可能还希望使用更复杂的数据库设计,以及更高级的Tkinter控件和布局。

  • 24
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,我们需要在 Android Studio 中创建一个 SQLite 数据。 1. 在项目中创建一个新的文件夹,命名为“database”或者其他你喜欢的名称。 2. 在该文件夹下创建一个新的类,命名为“DatabaseHelper”。 3. 在该类中,继承“SQLiteOpenHelper”类,并重写“onCreate”和“onUpgrade”方法。 ```java public class DatabaseHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "myDatabase.db"; private static final int DATABASE_VERSION = 1; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { // 创建表格 String sql = "CREATE TABLE IF NOT EXISTS student (" + "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT, " + "age INTEGER)"; db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // 更新表格 String sql = "DROP TABLE IF EXISTS student"; db.execSQL(sql); onCreate(db); } } ``` 在这个例子中,我们创建了一个名为“myDatabase.db”的数据,以及一个名为“student”的表格(包含三个字段:_id、name、age)。如果该表格不存在,则在“onCreate”方法中创建该表格。如果该表格已经存在,但版本号发生了变化,则在“onUpgrade”方法中更新该表格。 接下来,我们需要创建一个“DataHelper”类来实现数据增删功能。 ```java public class DataHelper { private DatabaseHelper dbHelper; private SQLiteDatabase db; public DataHelper(Context context) { dbHelper = new DatabaseHelper(context); db = dbHelper.getWritableDatabase(); } public void insert(String name, int age) { ContentValues cv = new ContentValues(); cv.put("name", name); cv.put("age", age); db.insert("student", null, cv); } public void update(int id, String name, int age) { ContentValues cv = new ContentValues(); cv.put("name", name); cv.put("age", age); db.update("student", cv, "_id = ?", new String[] { String.valueOf(id) }); } public void delete(int id) { db.delete("student", "_id = ?", new String[] { String.valueOf(id) }); } public Cursor queryAll() { Cursor cursor = db.query("student", null, null, null, null, null, null); return cursor; } public Cursor queryById(int id) { Cursor cursor = db.query("student", null, "_id = ?", new String[] { String.valueOf(id) }, null, null, null); return cursor; } public void close() { db.close(); dbHelper.close(); } } ``` 在这个例子中,我们创建了一个“DataHelper”类,用于实现增删功能。我们在该类中创建了以下方法: 1. “insert”方法:用于向表格中插入数据。 2. “update”方法:用于更新表格中的数据。 3. “delete”方法:用于删除表格中的数据。 4. “queryAll”方法:用于询表格中的所有数据。 5. “queryById”方法:用于根据ID询表格中的数据。 6. “close”方法:用于关闭数据连接。 最后,我们可以在 Activity 中调用这些方法来实现具体的操作。例如: ```java DataHelper dataHelper = new DataHelper(this); dataHelper.insert("Tom", 20); // 插入一条数据 dataHelper.update(1, "Jerry", 22); // 更新一条数据 dataHelper.delete(1); // 删除一条数据 Cursor cursor = dataHelper.queryAll(); // 询所有数据 while (cursor.moveToNext()) { int id = cursor.getInt(cursor.getColumnIndex("_id")); String name = cursor.getString(cursor.getColumnIndex("name")); int age = cursor.getInt(cursor.getColumnIndex("age")); Log.d("SQLite", "_id=" + id + ", name=" + name + ", age=" + age); } cursor.close(); dataHelper.close(); // 关闭数据连接 ``` 这样,就可以实现一个简单的 SQLite 数据增删功能了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值