提问人:dionysus 提问时间:9/23/2023 最后编辑:dionysus 更新时间:9/28/2023 访问量:55
npgsql C# 更新参数化语句 [duplicate]
Npgsql C# Update Parameterized Statement [duplicate]
问:
我打算在下面用 C# 执行参数化更新语句。我的解决方案不使用 Dapper,因此以下帖子(带有 Dapper 和 npgsql 的 Postgres Interval 不起作用)不适用。
NpgsqlConnection _command = _dataSource.CreateCommand(
"UPDATE \"BulkProposal\" SET \"UploadDataJson\" = NULL WHERE \"CreatedDate\" <= NOW() - INTERVAL @deleteInterval 'days' AND \"UploadDataJson\" is not NULL;");
_command.Parameters.AddWithValue("deleteInterval", _deleteIntervalInDays);
_npgsqlConnection.Open();
recordsDeleted = await _command.ExecuteNonQueryAsync();
执行上述语句时,我收到以下错误:
Unexpected Exception: 42601: syntax error at or near "$1"
POSITION: 92 | Exception Details: Npgsql.PostgresException (0x80004005): 42601: syntax error at or near "$1"
POSITION: 92
at Npgsql.Internal.NpgsqlConnector.<ReadMessage>g__ReadMessageLong|233_0(NpgsqlConnector connector, Boolean async, DataRowLoadingMode dataRowLoadingMode, Boolean readingNotifications, Boolean isReadingPrependedMessage)
at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)
at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlDataSourceCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlDataSourceCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteNonQuery(Boolean async, CancellationToken cancellationToken)
at BulkProposalDataPurge.BulkProposalDataPurge.FunctionHandler() in /home/abell/dev/proposal-service-lambdas/BulkProposalDataPurge.cs:line 53
Exception data:
Severity: ERROR
SqlState: 42601
MessageText: syntax error at or near "$1"
Position: 92
File: scan.l
Line: 1188
Routine: scanner_yyerror
问题似乎与
@deleteInterval 'days'
我还尝试了
'@deleteInterval days'
不确定如何解决此问题。
答:
-1赞
Maimoona Abid
9/23/2023
#1
在 SQL 查询中使用参数的方式是导致问题的原因。在 Npgsql 中使用参数化查询时,参数名称不需要包含在 SQL 语句本身的单引号中。相反,请完全按原样使用参数名称。请尝试以下代码,我在其中更改了您的 SQL 语句。
NpgsqlConnection _npgsqlConnection = _dataSource.CreateCommand(
"UPDATE \"BulkProposal\" SET \"UploadDataJson\" = NULL WHERE \"CreatedDate\" <= NOW() - INTERVAL @deleteInterval days AND \"UploadDataJson\" is not NULL;");
_npgsqlConnection.Parameters.AddWithValue("deleteInterval", _deleteIntervalInDays);
_npgsqlConnection.Open();
recordsDeleted = await _npgsqlConnection.ExecuteNonQueryAsync();
在运行此代码之前,请确保_deleteIntervalInDays设置为正确的数字;它应该是您打算用于间隔的天数。 希望它能:)
评论
@
_command.Parameters.AddWithValue("@deleteInterval", _deleteIntervalInDays);