mysql - 通过 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()
}
解决方案
我找到了解决方案:
$outdat = "NULL"
...
$MySqlCommand.CommandText = "INSERT INTO order_all_test (order_id, shop_id, hgsp_out_date) VALUES ('$inoid', '$insid', $outdat);"
所以诀窍是省略 sql 中的单引号。
推荐阅读
- google-play - Playstore 应用更新被拒绝 - 免责声明/来源:缺少明确的信息来源/免责声明
- python - python中的索引错误,请帮助修复
- scheme - 为什么我的结果中会出现“列表”一词?
- c++ - Visual Studio 2019 使用 32 位 FileTracker 和 64 位工具集
- java - 我应该如何实例化列表
- > 在 Java 中
- kotlin - 使用 Kotlin 的地图委托同步对可变字段的访问
- javascript - 为什么videojs在空格键上切换全屏,切换播放/暂停
- angular - Angular 2+ NGXS:状态在指令中未定义,尽管状态为默认值
- javascript - Javascript/JSP 遍历 Datatable 并计算发生次数
- sql - 如何通过替换各种文本的字符串来更新 sql 记录文本?