57 lines
1.6 KiB
Python
57 lines
1.6 KiB
Python
|
|
import pymysql
|
||
|
|
|
||
|
|
# 数据库配置
|
||
|
|
db_config = {
|
||
|
|
'host': "47.106.222.181",
|
||
|
|
'user': "group3",
|
||
|
|
'password': 'group3',
|
||
|
|
'database': 'ClassDB',
|
||
|
|
'port':25083
|
||
|
|
}
|
||
|
|
|
||
|
|
def con_mysql(sql_code, params=None):
|
||
|
|
conn = None
|
||
|
|
try:
|
||
|
|
conn = pymysql.connect(** db_config)
|
||
|
|
conn.ping(reconnect=True)
|
||
|
|
cursor = conn.cursor()
|
||
|
|
print(f"执行SQL: {sql_code}")
|
||
|
|
print(f"参数: {params}")
|
||
|
|
|
||
|
|
# 执行SQL
|
||
|
|
if params:
|
||
|
|
cursor.execute(sql_code, params)
|
||
|
|
else:
|
||
|
|
cursor.execute(sql_code)
|
||
|
|
|
||
|
|
# 增/删/改操作
|
||
|
|
if sql_code.strip().upper().startswith(('INSERT', 'UPDATE', 'DELETE')):
|
||
|
|
conn.commit()
|
||
|
|
result = {
|
||
|
|
'success': True,
|
||
|
|
'affected_rows': cursor.rowcount
|
||
|
|
}
|
||
|
|
# 对INSERT操作额外返回自增ID
|
||
|
|
if sql_code.strip().upper().startswith('INSERT'):
|
||
|
|
result['lastrowid'] = cursor.lastrowid
|
||
|
|
return result
|
||
|
|
|
||
|
|
# 查询操作
|
||
|
|
elif sql_code.strip().upper().startswith('SELECT'):
|
||
|
|
data = cursor.fetchall()
|
||
|
|
columns = [col[0] for col in cursor.description]
|
||
|
|
return {
|
||
|
|
'success': True,
|
||
|
|
'data': [dict(zip(columns, row)) for row in data]
|
||
|
|
}
|
||
|
|
|
||
|
|
return {'success': True}
|
||
|
|
|
||
|
|
except pymysql.MySQLError as err:
|
||
|
|
if conn:
|
||
|
|
conn.rollback()
|
||
|
|
return {'success': False, 'error': f"{type(err).__name__}: {err}"}
|
||
|
|
finally:
|
||
|
|
if conn:
|
||
|
|
conn.close()
|