Nic*_*las 0 c# sql oracle odp.net sql-update
我有一个可以在 SQL Developer 中运行的小型更新查询。
UPDATE people
SET months = 8
WHERE number = 599
Run Code Online (Sandbox Code Playgroud)
非常坦率的。它有效 - 这在 C# 中也有效。问题是当我想使用参数(适用于数字但不适用于月份)时,它将停止工作。
我在 C# 中有这样的代码:
using (OracleConnection con = new OracleConnection(connectionString))
{
con.Open();
OracleCommand command = con.CreateCommand();
command.CommandType = CommandType.Text;
command.CommandText = "UPDATE people " +
"SET months = :months " +
"WHERE number = :number";
command.Parameters.Add(":number", OracleDbType.Int32).Value = number;
command.Parameters.Add(":months", OracleDbType.Int32).Value = months;
command.ExecuteNonQuery();
}
Run Code Online (Sandbox Code Playgroud)
它们都是oracle中的Number类型,我尝试将OracleDbType更改为Decimal,但几乎一切都没有成功。奇怪的是, :number 参数有效,但几个月没有更新(它不会崩溃,只是不更新)。但是,如果我将 :months 参数更改为 7 这样的静态值 - 它将起作用。
好吧,我发现为什么这不起作用,这不是因为冒号(您可以在参数中添加冒号而不会出现问题):
command.Parameters.Add(":months", OracleDbType.Int32).Value = months;
Run Code Online (Sandbox Code Playgroud)
问题是我添加参数的顺序与使用它们的顺序不同。
因此,如果在 SQL 语句中按特定顺序添加参数,则在添加 OracleCommand.Parameters 时应遵循该顺序,如下所示:
using (OracleConnection con = new OracleConnection(connectionString))
{
con.Open();
OracleCommand command = con.CreateCommand();
command.CommandType = CommandType.Text;
command.CommandText = "UPDATE people " +
"SET months = :months " +
"WHERE number = :number";
command.Parameters.Add(":months", OracleDbType.Int32).Value = months;
command.Parameters.Add(":number", OracleDbType.Int32).Value = number;
command.ExecuteNonQuery();
}
Run Code Online (Sandbox Code Playgroud)