通过Powershell在MySQL中插入空值

时间:2019-05-14 17:40:31

标签: mysql powershell

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

我已经用$ 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()
            }

1 个答案:

答案 0 :(得分:1)

我找到了解决方法:

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

因此,诀窍是在sql中省略单引号。