You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
44 lines
1.2 KiB
44 lines
1.2 KiB
6 months ago
|
import pymysql
|
||
|
|
||
|
# 数据库连接配置
|
||
|
db_config = {
|
||
|
'host': 'localhost', # 数据库地址
|
||
|
'user': 'your_username', # 数据库用户名
|
||
|
'password': 'your_password', # 数据库密码
|
||
|
'database': 'word', # 数据库名
|
||
|
'charset': 'utf8mb4', # 字符编码
|
||
|
}
|
||
|
|
||
|
# 待插入的数据
|
||
|
data_to_insert = [
|
||
|
(1, 'abandon vt.旬弃;形弃,萨瑟'),
|
||
|
(2, 'ability n.能力;能耐,乃炸'),
|
||
|
# ... 其他数据 ...
|
||
|
# 注意:这里的每一项都是一个元组,格式为(序号, 内容)
|
||
|
]
|
||
|
|
||
|
# 连接数据库并尝试插入数据
|
||
|
try:
|
||
|
connection = pymysql.connect(**db_config)
|
||
|
cursor = connection.cursor()
|
||
|
|
||
|
# 执行批量插入
|
||
|
for item in data_to_insert:
|
||
|
xuhao, neirong = item
|
||
|
insert_sql = "INSERT INTO word (xuhao, neirong) VALUES (%s, %s)"
|
||
|
cursor.execute(insert_sql, (xuhao, neirong))
|
||
|
|
||
|
# 提交事务
|
||
|
connection.commit()
|
||
|
print("数据插入成功!")
|
||
|
except Exception as e:
|
||
|
print(f"数据插入失败,错误信息:{e}")
|
||
|
# 发生错误时回滚事务
|
||
|
if connection:
|
||
|
connection.rollback()
|
||
|
finally:
|
||
|
# 关闭游标和连接
|
||
|
if cursor:
|
||
|
cursor.close()
|
||
|
if connection:
|
||
|
connection.close()
|