python - 使用 "load infile data"时将真假字符串转换为 bool 值

标签 python mysql sql-server mysql-python

我需要将数据从 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 of t1.column1, and assigns the second input column to a user variable that is subjected to a division operation before being used for the value of t1.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/

相关文章:

python - pygrib 数据在 359.5 到 360 度之间的 matplotlib 图上的白色区域

php - IF THEN 在 mySQL 查询中

sql-server - 在主键/聚集索引中使用 GUID

python - 如何在Python中正确加载数据文件

python - 太多值无法解包 for 循环计数列表中的值时出现错误

python - 列表理解中的字符串格式

php - 如何在单个 PHP 文件中使用不同的表单?

php - 回显从数据库中检索到的行的 session

sql - Decimal(19,4) 或 Decimal(19.2) - 我应该使用哪个?

asp.net - 如何创建/使用 MembershipProvider?