在Python中,可以使用各種庫來編寫數據庫界面,其中最常用的庫之一是Tkinter。以下是使用Tkinter編寫一個簡單的數據庫界面的示例代碼:
import tkinter as tk
import sqlite3
def create_table():
conn = sqlite3.connect('mydatabase.db')
c = conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS students (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)')
conn.commit()
conn.close()
def insert_data():
name = name_entry.get()
age = age_entry.get()
conn = sqlite3.connect('mydatabase.db')
c = conn.cursor()
c.execute('INSERT INTO students (name, age) VALUES (?, ?)', (name, age))
conn.commit()
conn.close()
name_entry.delete(0, tk.END)
age_entry.delete(0, tk.END)
def display_data():
conn = sqlite3.connect('mydatabase.db')
c = conn.cursor()
c.execute('SELECT * FROM students')
data = c.fetchall()
conn.close()
for row in data:
print(row)
root = tk.Tk()
name_label = tk.Label(root, text="Name:")
name_label.pack()
name_entry = tk.Entry(root)
name_entry.pack()
age_label = tk.Label(root, text="Age:")
age_label.pack()
age_entry = tk.Entry(root)
age_entry.pack()
create_table_button = tk.Button(root, text="Create Table", command=create_table)
create_table_button.pack()
insert_data_button = tk.Button(root, text="Insert Data", command=insert_data)
insert_data_button.pack()
display_data_button = tk.Button(root, text="Display Data", command=display_data)
display_data_button.pack()
root.mainloop()
這個例子創建了一個基本的Tkinter窗口,可以輸入學生姓名和年齡,并將數據插入到SQLite數據庫中。還提供了一個按鈕來創建數據表,插入數據和顯示數據。