【问题标题】:SQL file executes in MySQL workbench but not in pythonSQL 文件在 MySQL 工作台中执行,但不在 python 中
【发布时间】:2017-11-14 22:16:09
【问题描述】:

我正在编写一个 python 脚本来将数据从一个 MySQL 数据库迁移到另一个。该脚本加载一个由 mysqldump 转储的 sql 文件,并将命令拆分为类似于this SO question。当我使用 python-mysql 库在 python 2.7 中执行脚本时,python 输出以下错误:

_mysql_exceptions.ProgrammingError: (1064, 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'\'\\"><script>alert(1)\' at line 1')

检查相关文件,我发现 python 在尝试执行包含 6 条记录的大量插入语句时失败,如下所示:

('58cd48g5158b8','2015-12-02 16:05:25','\"><script>alert(1);</script>','12.16.98.253')

但是,如果我要在 MySQL Workbench 中执行相同的文件,它会在没有错误的情况下完成。

1。为什么mysql服务器执行文件没有问题,但是mysql-python报错?

2。为什么python会把字符串当作SQL语法错误?

注意:该表是脚本中第 13 个要处理的表,插入命令是该表的第 18 个命令;所以,我怀疑这是我的代码的问题。

相关Python代码

def loadMigrationScriptForTable(self, tableName, schemaName='obfuscated'):
    fileName = 'obfuscated' + schemaName + '.' + tableName + '.sql'
    fileDir = self.conf.get('obfuscated', 'obfuscated')
    workfile = os.path.join(fileDir, fileName)
    try:
        file = open(workfile, 'r')
        contents = file.read()
        return contents
    except IOError:
        return Exception('File does not exist: '+workfile)

# Migrate tables whose table definition has not been altered but row counts has changed.
def migrateTablesWithUnmodifiedDefinition(self):
    tables = self.conf.get('obfuscated', 'obfuscated').split(', ')
    responses = []
    for table in tables:
        # Load SQL file (as string)
        MySQLScript = self.loadMigrationScriptForTable(table)
        if(isinstance(MySQLScript, Exception)):
            print table, MySQLScript
            continue # Skip remaining code if file couldn't load.

        # Split commands
        sqlCommands = MySQLScript.split(';')
        for sqlCommand in sqlCommands:
            # Execute SQL file.
            print table, sqlCommand[0:99]
            response = self.db.executeScript(sqlCommand)
            print "        ", response
            responses.append(response)

def executeScript(self, script):
    self._DB.connection.execute(script)

【问题讨论】:

  • 我确定它您的代码有问题,但是由于您没有发布任何内容,我们不能说任何一种方式。
  • 更新了相关代码。

标签: python mysql data-migration


【解决方案1】:

正如Daniel Roseman 所暗示的,这是我的代码的问题。在解析和拆分mysqldump生成的sql文件时,应该根据分号和换行符进行拆分,否则string.split会在字符串中拆分分号。

错误代码

# Split commands
sqlCommands = MySQLScript.split(';')

固定代码

# Split commands
sqlCommands = MySQLScript.split(';\n')

操作系统说明

注意:这适用于 Windows;但是,我还没有在 *nix 上测试过它。如果在 *nix 上运行,使用string.splitlines 可能更谨慎。

# Split commands
sqlCommands = MySQLScript.splitlines()

【讨论】:

  • 我添加了操作系统注释,以防\nCR LF 行终止符产生影响。
猜你喜欢
  • 1970-01-01
  • 2012-12-06
  • 1970-01-01
  • 1970-01-01
  • 2014-09-29
  • 2017-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多