I receive data from a webservice and want to insert it into a MySQL database with Powershell. Unfortunatly datetime values ($outdat) could get null. But I do not manage to insert a null value in that case. Inserting dates works. Here is the basic code:
I have already tried with $outdat = $null, '' and [DBNull]::Value, none of them works.
$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()
}
"INSERT INTO order_all_test (order_id, shop_id) VALUES ('$inoid', '$insid');"(eliminating a column fromINSERT INTOshould leave that column uninitialized however, at the moment, I can't verify whether it's the same as dbnull )