我需要将数据从 MSSQL (Microsoft SQL Server) 传输到 MySQL,对我来说最好的选择是编写一个 python 脚本,将数据从 MSSQL 导出为 csv,然后将此 csv 导入 mysql。到目前为止,这个过程对我来说效果很好(我没有寻找其他方法来做到这一点)。
从 MSSQL 到 MySQL 的数据类型转换是这样完成的:
MSSQL_MySQL_MAP = {
'nvarchar' : 'varchar',
'varchar' : 'varchar',
'bit' : 'boolean',
'smallint' : 'smallint',
'int' : 'int',
'datetime' : 'datetime',
'timestamp' : 'datetime',
'ntext' : 'longtext',
'real' : 'double',
'image' : 'BLOB',
'float' : 'float',
'money' : 'decimal',
}
使用以下命令将导出的 csv 导入 MySQL。
"""LOAD DATA INFILE '%s/%s' REPLACE INTO TABLE %s FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'"""
我遇到的情况是 MSSQL 中有一个“位”数据类型,导出的 CSV 包含一个 True of False 字符串,如下所示:
22294,501,q4h,12 ,False,False,None,False,None,None,None,0,None,None
让 MySQL 理解 True 或 False 字符串是 bool 值 1 或 0 并正确导入它的最佳方法是什么?目前,我收到以下警告:
Warning: Incorrect integer value: 'False' for column 'system_code' at row 7
有没有一种方法可以将一些参数与加载文件数据一起传递来完成此操作?
最佳答案
根据 LOAD DATA INFILE
Syntax 记录:
By default, when no column list is provided at the end of the
LOAD DATA INFILE
statement, input lines are expected to contain a field for each table column. If you want to load only some of a table's columns, specify a column list:LOAD DATA INFILE 'persondata.txt' INTO TABLE persondata (col1,col2,...);
You must also specify a column list if the order of the fields in the input file differs from the order of the columns in the table. Otherwise, MySQL cannot tell how to match input fields with table columns.
The column list can contain either column names or user variables. With user variables, the
SET
clause enables you to perform transformations on their values before assigning the result to columns.User variables in the
SET
clause can be used in several ways. The following example uses the first input column directly for the value oft1.column1
, and assigns the second input column to a user variable that is subjected to a division operation before being used for the value oft1.column2
:LOAD DATA INFILE 'file.txt' INTO TABLE t1 (column1, @var1) SET column2 = @var1/100;
在您的情况下,您可以执行类似 SET boolean_column := @dummy_variable = 'True'
的操作。
关于python - 使用 "load infile data"时将真假字符串转换为 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17620147/