1.填充数据
import sqlite3
# 连接到数据库(如果数据库不存在,则会创建一个新的数据库)
conn = sqlite3.connect(r'C:\Users\Administrator\database.sqlite3')
# 创建游标对象
cursor = conn.cursor()
# 创建renyuan表
cursor.execute('''CREATE TABLE renyuan (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
age INTEGER,
gender TEXT,
wealth REAL,
source TEXT,
industry TEXT,
country TEXT,
rank INTEGER
)''')
# 插入数据
data = [
('马云', 57, '男', 450, '阿里巴巴', '电子商务', '中国', 1),
('马化腾', 50, '男', 440, '腾讯', '互联网', '中国', 2),
('许家印', 63, '男', 430, '恒大集团', '房地产', '中国', 3),
('杨惠妍', 40, '女', 410, '中国恒大', '房地产', '中国', 4),
('张一鸣', 39, '男', 400, '字节跳动', '互联网', '中国', 5),
('王健林', 67, '男', 390, '万达集团', '房地产', '中国', 6),
('王卫', 59, '男', 380, '中国联通', '电信', '中国', 7),
('雷军', 53, '男', 370, '小米', '电子产品', '中国', 8),
('刘强东', 48, '男', 360, '京东', '电子商务', '中国', 9),
('丁磊', 49, '男', 350, '网易', '互联网', '中国', 10),
('宗庆后', 75, '男', 340, '娃哈哈', '饮料', '中国', 11),
('许荣茂', 64, '男', 330, '恒力集团', '化工', '中国', 12),
('刘永好', 71, '男', 320, '碧桂园', '房地产', '中国', 13),
('孙正义', 64, '男', 310, '软银', '投资', '中国', 14),
('孙宏斌', 59, '男', 300, '乐视网', '互联网', '中国', 15),
('潘石屹', 59, '男', 290, 'SOHO中国', '房地产', '中国', 16),
('许家标', 62, '男', 280, '恒大集团', '房地产', '中国', 17),
('姚振华', 59, '男', 270, '中国国电集团', '能源', '中国', 18),
('李彦宏', 53, '男', 260, '百度', '互联网', '中国', 19),
('王石', 73, '男', 250, '万科企业', '房地产', '中国', 20),
]
cursor.executemany('INSERT INTO renyuan (name, age, gender, wealth, source, industry, country, rank) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', data)
# 提交事务
conn.commit()
# 关闭游标和数据库连接
cursor.close()
conn.close()
2.显示及查询数据
import sqlite3
from flask import Flask, render_template_string, request, jsonify
import threading
import tkinter as tk
import time
import os
import signal
# 数据库路径
DB_PATH = "C:/Users/Administrator/database.sqlite3"
# 创建Flask应用
app = Flask(__name__)
# 全局变量,用于判断Flask进程的运行状态
running = False
# 创建Tkinter窗口
window = tk.Tk()
window.title("数据库查询工具")
window.geometry("320x320")
# 文字状态指示控件
status_label = tk.Label(window, text="已停止", font=("Arial", 12))
status_label.pack(pady=20)
# 切换运行/停止按钮点击事件
def toggle_flask():
global running
if running:
# 停止Flask进程
os.kill(os.getpid(), signal.SIGINT)
running = False
status_label.config(text="已停止")
else:
# 启动Flask进程
threading.Thread(target=start_flask).start()
# 切换运行/停止按钮
toggle_button = tk.Button(window, text="切换运行/停止", command=toggle_flask)
toggle_button.pack(pady=10)
# 退出程序按钮点击事件
def exit_program():
# 关闭Flask进程
os.kill(os.getpid(), signal.SIGINT)
time.sleep(1)
# 关闭Tkinter窗口
window.destroy()
# 退出程序按钮
exit_button = tk.Button(window, text="退出程序", command=exit_program)
exit_button.pack(pady=10)
# 启动Flask进程的函数
def start_flask():
global running
running = True
status_label.config(text="正在运行")
app.run()
# Flask路由:根路径
@app.route('/')
def index():
table_data = get_all_data()
columns = get_table_columns()
return render_template_string('''
<h1>数据库查询工具</h1>
<h2>renyuan数据表</h2>
<table border="1">
<thead>
<tr>
{% for column in columns %}
<th>{{ column }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for row in table_data %}
<tr>
{% for value in row.values() %}
<td>{{ value }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
<h2>精确查询</h2>
<select id="column">
<option value="">选择列名</option>
{% for column in columns %}
<option value="{{ column }}">{{ column }}</option>
{% endfor %}
</select>
<input type="text" id="search" placeholder="输入查询信息">
<button onclick="search()">查询</button>
<table id="search-results" border="1">
<thead>
<tr>
{% for column in columns %}
<th>{{ column }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
</tbody>
</table>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
function search() {
var column = $("#column").val();
var search = $("#search").val();
$.post("/search", {column: column, search: search}, function(data) {
var tbody = $("#search-results tbody");
tbody.empty();
$.each(data, function(index, row) {
var tr = $("<tr></tr>");
{% for column in columns %}
tr.append("<td>" + row["{{ column }}"] + "</td>");
{% endfor %}
tbody.append(tr);
});
});
}
</script>
''', table_data=table_data, columns=columns)
# Flask路由:精确查询
@app.route('/search', methods=['POST'])
def search():
column = request.form['column']
search = request.form['search']
data = search_data(column, search)
return jsonify(data)
# 查询数据库中的所有数据
def get_all_data():
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("SELECT * FROM renyuan")
rows = cursor.fetchall()
columns = [column[0] for column in cursor.description]
data = [dict(zip(columns, row)) for row in rows]
conn.close()
return data
# 获取数据库表的列名
def get_table_columns():
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("PRAGMA table_info(renyuan)")
columns = [column[1] for column in cursor.fetchall()]
conn.close()
return columns
# 根据列名和查询信息进行精确查询
def search_data(column, search):
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute(f"SELECT * FROM renyuan WHERE {column}=?", (search,))
rows = cursor.fetchall()
columns = [column[0] for column in cursor.description]
data = [dict(zip(columns, row)) for row in rows]
conn.close()
return data
# 运行Tkinter窗口主循环
window.mainloop()
评论前必须登录!
注册