首页 > 解决方案 > 通过 Powershell 在 MySQL 中插入 Null 值

问题描述

我从 Web 服务接收数据,并希望使用 Powershell 将其插入 MySQL 数据库。不幸的是,日期时间值 ($outdat) 可能为空。但在这种情况下,我无法插入空值。插入日期有效。这是基本代码:

我已经尝试过使用 $outdat = $null, '' 和 [DBNull]::Value,它们都不起作用。

$MySQLAdminUserName = 'xxx'
$MySQLAdminPassword = 'xxx'
$MySQLDatabase = 'xxx'
$MySQLHost = 'localhost'
$ConnectionString = "server=" + $MySQLHost + ";port=3306;uid=" + $MySQLAdminUserName + ";pwd=" + $MySQLAdminPassword + ";database="+$MySQLDatabase

    Try {
        [void][System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")
        $Connection = New-Object MySql.Data.MySqlClient.MySqlConnection
        $Connection.ConnectionString = $ConnectionString
        $Connection.Open()

        $MySqlCommand = New-Object MySql.Data.MySqlClient.MySqlCommand
        $MySqlCommand.Connection = $Connection

        $inoid = "123457"
        $outdat = [DBNull]::Value
        $insid = "Hello World"


            $MySqlCommand.CommandText = "INSERT INTO order_all_test (order_id, shop_id, hgsp_out_date) VALUES ('$inoid', '$insid', '$outdat');"
            $MySqlCommand.ExecuteNonQuery() | Out-Null
            $lastId = $MySqlCommand.get_LastInsertedId()

        }

        Catch {
            Write-Host "ERROR : Unable to run query : $query `n$Error[0]"
        }

        Finally {
            $Connection.Close()
            }

标签: mysqlpowershell

解决方案


我找到了解决方案:

$outdat = "NULL"
...
$MySqlCommand.CommandText = "INSERT INTO order_all_test (order_id, shop_id, hgsp_out_date) VALUES ('$inoid', '$insid', $outdat);"

所以诀窍是省略 sql 中的单引号。


推荐阅读