【发布时间】: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