You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python脚本导入SQL Dump到MariaDB时出现Error 1064语法错误

问题原因与解决方案

核心问题

你手动用split(';')拆分SQL语句的方式是错误的。你的content字段值里包含分号(比如Happy Hours 3 Hours Package;19;2016-11-28 16:00:00...),这会把一条完整的INSERT语句拆成多个不完整的片段,导致执行时语法错误。而DBeaver会按照SQL语法规则解析语句,能识别字符串内部的分号,不会误拆分,所以可以成功执行。

修复方案

使用mysql.connector提供的multi=True参数来批量执行SQL语句,不需要手动拆分:

修改后的脚本:

import mysql.connector

# Database connection details
host = 'localhost'
port = 3306
user = 'admin'
password = 'password'
database = 'example'

# SQL file path
sql_file = 'file_location'

try:
    connection = mysql.connector.connect(
        host=host,
        port=port,
        user=user,
        password=password,
        database=database
    )
    cursor = connection.cursor()

    with open(sql_file, 'r', encoding='utf-8') as file:
        sql_statements = file.read()

    # 使用multi=True执行多个SQL语句
    for result in cursor.execute(sql_statements, multi=True):
        pass

    connection.commit()
    print('Data imported successfully.')

except mysql.connector.Error as error:
    print('Error:', error)

finally:
    if 'connection' in locals() and connection.is_connected():
        cursor.close()
        connection.close()

额外注意事项

  • 打开文件时指定encoding='utf-8',避免因编码问题导致的字符串解析错误;
  • 如果SQL文件包含大量数据,建议分批执行或者使用LOAD DATA INFILE等更高效的导入方式,避免内存占用过高;
  • 确保你的mysql.connector版本是最新的,避免因版本兼容性导致的问题。

内容的提问来源于stack exchange,提问作者user6248190

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 16:42:21