Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
CHANGED
@@ -28,17 +28,26 @@ def get_db_connection():
|
|
28 |
|
29 |
|
30 |
def save_to_db(table, data):
|
31 |
-
conn = None
|
32 |
try:
|
|
|
|
|
|
|
|
|
|
|
33 |
conn = get_db_connection()
|
34 |
with conn.cursor() as cursor:
|
35 |
-
|
36 |
columns = ', '.join(data.keys())
|
|
|
37 |
sql = f"INSERT INTO {table} ({columns}) VALUES ({placeholders})"
|
38 |
cursor.execute(sql, list(data.values()))
|
39 |
conn.commit()
|
40 |
-
except
|
41 |
-
print(f"
|
|
|
|
|
|
|
42 |
finally:
|
43 |
if conn:
|
44 |
conn.close()
|
|
|
28 |
|
29 |
|
30 |
def save_to_db(table, data):
|
31 |
+
conn = None
|
32 |
try:
|
33 |
+
# 表名白名单验证
|
34 |
+
valid_tables = ["entities", "relations"]
|
35 |
+
if table not in valid_tables:
|
36 |
+
raise ValueError(f"Invalid table: {table}")
|
37 |
+
|
38 |
conn = get_db_connection()
|
39 |
with conn.cursor() as cursor:
|
40 |
+
# 使用参数化查询避免注入
|
41 |
columns = ', '.join(data.keys())
|
42 |
+
placeholders = ', '.join(['%s'] * len(data))
|
43 |
sql = f"INSERT INTO {table} ({columns}) VALUES ({placeholders})"
|
44 |
cursor.execute(sql, list(data.values()))
|
45 |
conn.commit()
|
46 |
+
except pymysql.Error as e: # 细化异常类型
|
47 |
+
print(f"数据库错误: {e}")
|
48 |
+
conn.rollback()
|
49 |
+
except ValueError as e: # 表名无效
|
50 |
+
print(f"参数错误: {e}")
|
51 |
finally:
|
52 |
if conn:
|
53 |
conn.close()
|