parent
fe202c017a
commit
e622d3554e
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -1,69 +1,114 @@
|
||||
import pymysql
|
||||
import pymysql.cursors
|
||||
import tkinter as tk
|
||||
from tkinter import filedialog
|
||||
import os
|
||||
|
||||
# 数据库连接参数
|
||||
DB_HOST = 'localhost' # 数据库主机
|
||||
DB_USER = 'root' # 数据库用户名
|
||||
DB_PASSWORD = '123456' # 数据库密码
|
||||
DB_NAME = 'file' # 数据库名
|
||||
|
||||
def create_connection(host, user, password, db):
|
||||
connection = None
|
||||
try:
|
||||
connection = pymysql.connect(
|
||||
host=host,
|
||||
user=user,
|
||||
password=password,
|
||||
db=db,
|
||||
charset='utf8mb4',
|
||||
cursorclass=pymysql.cursors.DictCursor
|
||||
)
|
||||
print("Connection to MySQL DB successful")
|
||||
except pymysql.MySQLError as e:
|
||||
print(f"The error '{e}' occurred")
|
||||
|
||||
return connection
|
||||
|
||||
|
||||
def upload_file_to_db(connection, file_path):
|
||||
if not os.path.exists(file_path):
|
||||
print("File does not exist.")
|
||||
return
|
||||
# 创建表的SQL语句
|
||||
CREATE_TABLE_SQL = """
|
||||
CREATE TABLE IF NOT EXISTS images (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
filename VARCHAR(255),
|
||||
content LONGBLOB,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
"""
|
||||
|
||||
def create_table():
|
||||
connection = pymysql.connect(host=DB_HOST, user=DB_USER, password=DB_PASSWORD, db=DB_NAME)
|
||||
try:
|
||||
with open(file_path, 'rb') as file:
|
||||
# 读取文件二进制内容
|
||||
file_content = file.read()
|
||||
|
||||
cursor = connection.cursor()
|
||||
sql_query = """
|
||||
INSERT INTO file_storage (file_name, file_content)
|
||||
VALUES (%s, %s)
|
||||
"""
|
||||
# 获取文件名
|
||||
file_name = os.path.basename(file_path)
|
||||
# 执行SQL语句
|
||||
cursor.execute(sql_query, (file_name, pymysql.Binary(file_content)))
|
||||
connection.commit()
|
||||
print(f"File {file_name} has been uploaded successfully.")
|
||||
except pymysql.MySQLError as e:
|
||||
print(f"Error uploading file: {e}")
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute(CREATE_TABLE_SQL)
|
||||
connection.commit()
|
||||
print("Table 'images' created successfully.")
|
||||
finally:
|
||||
connection.close()
|
||||
def path_to_bytes():
|
||||
return filedialog.askopenfilename(filetypes=(("Image Files", "*.jpg;*.png;*.gif"), ("All Files", "*.*")))
|
||||
def upload_image():
|
||||
selected_image_path = path_to_bytes()
|
||||
if selected_image_path:
|
||||
with open(selected_image_path, 'rb') as image_file:
|
||||
image_content = image_file.read()
|
||||
|
||||
connection = pymysql.connect(host=DB_HOST, user=DB_USER, password=DB_PASSWORD, db=DB_NAME)
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
sql = "INSERT INTO images (filename, content) VALUES (%s, %s)"
|
||||
cursor.execute(sql, (os.path.basename(selected_image_path), pymysql.Binary(image_content)))
|
||||
connection.commit()
|
||||
print(f"Image '{selected_image_path}' uploaded successfully.")
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
# 数据库连接配置
|
||||
host = 'localhost'
|
||||
database = 'file'
|
||||
user = 'root'
|
||||
password = '123456'
|
||||
def delete_image():
|
||||
# 获取用户输入的图像ID
|
||||
image_id = tk.simpledialog.askinteger("删除图片", "请输入需要删除的图像ID:")
|
||||
if image_id is not None:
|
||||
connection = pymysql.connect(host=DB_HOST, user=DB_USER, password=DB_PASSWORD, db=DB_NAME)
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
# 查询图像信息
|
||||
cursor.execute("SELECT * FROM images WHERE id = %s", (image_id,))
|
||||
image_data = cursor.fetchone()
|
||||
if image_data:
|
||||
# 输出图像信息
|
||||
print(f"Image Details:")
|
||||
for index, value in enumerate(image_data):
|
||||
column_name = cursor.description[index][0]
|
||||
print(f"{column_name}: {value}")
|
||||
# 提示用户确认删除
|
||||
confirmation = tk.messagebox.askyesno("Confirm Delete", f"是否删除图片ID为 {image_id}的图片?")
|
||||
if confirmation:
|
||||
# 执行删除操作
|
||||
sql = "DELETE FROM images WHERE id = %s"
|
||||
cursor.execute(sql, (image_id,))
|
||||
connection.commit()
|
||||
print(f"成功删除图片ID为 {image_id} 的图片.")
|
||||
else:
|
||||
print(f"没有发现图片ID为 {image_id}的图片.")
|
||||
except Exception as e:
|
||||
print(f"Error deleting image: {e}")
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
# 文件路径
|
||||
file_path = 'file_paths.txt'
|
||||
def download_image():
|
||||
# 获取用户输入的图像ID
|
||||
image_id = tk.simpledialog.askinteger("下载图片", "请输入需要下载的图像ID:")
|
||||
if image_id is not None:
|
||||
connection = pymysql.connect(host=DB_HOST, user=DB_USER, password=DB_PASSWORD, db=DB_NAME)
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
# 查询图像内容和文件名
|
||||
cursor.execute("SELECT content, filename FROM images WHERE id = %s", (image_id,))
|
||||
image_data = cursor.fetchone()
|
||||
if image_data:
|
||||
content, original_filename = image_data
|
||||
# 构建默认的保存文件名
|
||||
default_filename = os.path.splitext(original_filename)[0] + ".jpg"
|
||||
# 使用默认扩展名并允许用户选择保存位置
|
||||
save_path = filedialog.asksaveasfilename(initialfile=default_filename, defaultextension=".jpg", filetypes=[("JPEG Images", "*.jpg"), ("All Files", "*.*")])
|
||||
if save_path:
|
||||
try:
|
||||
with open(save_path, 'wb') as image_file:
|
||||
image_file.write(content)
|
||||
print(f"Image downloaded successfully to '{save_path}'.")
|
||||
except IOError as e:
|
||||
print(f"Error writing to file: {e}")
|
||||
else:
|
||||
print("Download cancelled.")
|
||||
else:
|
||||
print(f"No image found with ID {image_id}.")
|
||||
except Exception as e:
|
||||
print(f"Error downloading image: {e}")
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
# 创建数据库连接
|
||||
conn = create_connection(host, user, password, database)
|
||||
|
||||
if conn is not None:
|
||||
# 上传文件到数据库
|
||||
upload_file_to_db(conn, file_path)
|
||||
else:
|
||||
print("Failed to connect to the database.")
|
||||
|
||||
# 关闭连接(如果打开)
|
||||
if conn:
|
||||
conn.close()
|
||||
|
||||
|
@ -0,0 +1,18 @@
|
||||
from tkinter import filedialog
|
||||
import tkinter as tk
|
||||
from sql import *
|
||||
def upload_file_login():
|
||||
|
||||
new_window = tk.Tk()
|
||||
new_window.title("欢迎来到上传界面")
|
||||
new_window.geometry("600x200")
|
||||
|
||||
upload_file_button = tk.Button(new_window, text="上传图片", command=upload_image)
|
||||
upload_file_button.pack()
|
||||
|
||||
back_button = tk.Button(new_window, text="返回", command=new_window.destroy)
|
||||
back_button.pack()
|
||||
|
||||
new_window.mainloop()
|
||||
|
||||
|
After Width: | Height: | Size: 1.6 MiB |
After Width: | Height: | Size: 2.2 MiB |
Loading…
Reference in new issue