我试图在返回其标识值的同时插入到表中。但是会引发“索引超出数组范围”错误。我可以成功地在dbForge中执行查询,但是当我尝试使用oracle管理的数据访问权限在C#中执行查询时不能成功执行。 查询非常简单。如果我禁用事务,则该行会插入数据库中,但会出现错误并且无法获取返回值。
np.sqrt(data_entries + 0.25)
我试图在返回其标识值的同时插入到表中。但是会引发“索引超出数组范围”错误。我可以成功地在dbForge中执行查询,但是当我尝试使用oracle管理的数据访问权限在C#中执行查询时不能成功执行。 查询非常简单。如果我禁用事务,则该行会插入数据库中,但会出现错误并且无法获取返回值。
np.sqrt(data_entries + 0.25)
如果您有任何问题,请告诉我,
int newId = 0;
// NOTE,if you don't insert into field 'ID' you need to list fields
var sql = "insert into table1 (fld1,fd2) VALUES (97,'Mondon') RETURNING Id INTO :id";
try
{
using (var conn = new OracleConnection(_conStr))
{
using (var cmd = new OracleCommand(sql,conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new OracleParameter("id",OracleDbType.Int32,ParameterDirection.Output)); // this is output,not return
conn.Open();
var count = cmd.ExecuteNonQuery();
if (count > 0) // table can have a trigger so number of rows changed can be more than 1
{
// YOUR BIG MISCONCEPTION HERE (FIXED)
OracleDecimal val = (OracleDecimal)cmd.Parameters["id"].Value; // this returns special oracle struct
int newId = val.ToInt32(); // you can use val.IsNull but here it is not possible
}
else
throw new Exception("Value not inserted");
}
}
}
catch (Exception ex)
{
Logger.LogError(ex);
}
请注意,对于插入单个记录,不需要显式事务
,我认为您必须将插入内容封装到一个函数中
create function InsertTable1(n in integer,val in varchar2) return integer as
res integer;
begin
insert into table1 VALUES (n,val) RETURNING Id INTO res;
RETURN res;
end;
然后在您的应用程序中:
var query = @"BEGIN :0 := InsertTable1(97,'Mondon'); END;";
最好将输入值也定义为绑定参数,而不是静态字符串。
完整的动态解决方案可能与此类似:
create function InsertTable(cmd in varchar2) return integer as
res integer;
begin
EXECUTE IMMEDIATE cmd USING OUT res;
RETURN res;
end;
var query = @"BEGIN :0 := InsertTable('insert into table1 VALUES (97,''Mondon'') RETURNING Id INTO :res'); END;";