You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PowerShell向Oracle插入含时间的Date类型数据遇ORA-01830错误

问题描述

尝试使用PowerShell向Oracle数据库插入数据,代码如下:

$date = Get-Date -Format 'dd/MM/yyyy HH:mm:ss'

***Oracle Connection***

$Command.CommandText = "insert into Datetest VALUES ('$date')"
$command.ExecuteNonQuery()
$OracleConnection.Close()

目标SQL表首列为Date类型,要求格式为dd/MM/yyyy HH:mm:ss,但插入该格式数据时报错:

"ORA-01830: Datumsformatstruktur endet vor Umwandlung der gesamten Eingabezeichenfolge"

对应的英文错误:

"ORA-01830: date format picture ends before converting entire input string"

仅插入dd/mm/yyyy格式数据可成功,但时间部分会被置空,如何插入包含时间的日期数据?

解决方案

优先使用参数化查询(最安全可靠)

直接传递DateTime对象,让Oracle驱动自动处理日期格式,完全避免字符串解析问题,还能防范SQL注入:

$currentDate = Get-Date

# 假设$Command已关联Oracle连接并初始化完成
$Command.CommandText = "INSERT INTO Datetest VALUES (:inputDate)"
$dateParam = $Command.CreateParameter()
$dateParam.ParameterName = "inputDate"
$dateParam.OracleDbType = [Oracle.DataAccess.Client.OracleDbType]::Date
$dateParam.Value = $currentDate
$Command.Parameters.Add($dateParam)

$Command.ExecuteNonQuery()
$OracleConnection.Close()

用TO_DATE函数显式转换格式

如果坚持通过字符串传递数据,使用TO_DATE函数指定匹配的格式模板,注意用HH24代表24小时制:

$dateStr = Get-Date -Format 'dd/MM/yyyy HH:mm:ss'
$Command.CommandText = "INSERT INTO Datetest VALUES (TO_DATE('$dateStr', 'DD/MM/YYYY HH24:MI:SS'))"
$Command.ExecuteNonQuery()
$OracleConnection.Close()

临时修改会话日期格式

执行插入前修改当前会话的NLS_DATE_FORMAT,让Oracle自动识别你的日期字符串格式:

# 先设置会话日期格式
$Command.CommandText = "ALTER SESSION SET NLS_DATE_FORMAT = 'DD/MM/YYYY HH24:MI:SS'"
$Command.ExecuteNonQuery()

# 再执行插入操作
$dateStr = Get-Date -Format 'dd/MM/yyyy HH:mm:ss'
$Command.CommandText = "INSERT INTO Datetest VALUES ('$dateStr')"
$Command.ExecuteNonQuery()
$OracleConnection.Close()

内容的提问来源于stack exchange,提问作者AoT_1503

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 05:01:47