开发者

ODP.NET and parameters

I have built a common app that works with PostgreSQL and should work o开发者_如何学Gon Oracle.

However i'm getting strange errors when inserting records through a parametrized query.

My formatted query looks like this:

"INSERT INTO layer_mapping VALUES (@lm_id,@lm_layer_name,@lm_layer_file);"

Unlike Npgsql which documents how to use the parameters, i could not found how Oracle "prefers" them to be used. I could only find :1, :2, :3, for example.

I do not wanto use sequential parameters, i want to use them in a named way.

Is there a way to do it? Am i doing something wrong?

Thanks


You can use named parameters with ODP.NET like so:

using (var cx=new OracleConnection(connString)){
   using(var cmd=cx.CreateCommand()){
      cmd.CommandText="Select * from foo_table where bar=:bar";
      cmd.BindByName=true;
      cmd.Parameters.Add("bar",barValue);
      ///...
   }
}


I made this lib https://github.com/pedro-muniz/ODPNetConnect/blob/master/ODPNetConnect.cs

so you can do parameterized write and read like this:

ODPNetConnect odp = new ODPNetConnect();
if (!String.IsNullOrWhiteSpace(odp.ERROR))
{
    throw new Exception(odp.ERROR);
}

//Write:
string sql = @"INSERT INTO TABLE (D1, D2, D3)  VALUES (:D1, :D2, :D3)";

Dictionary<string, object> params = new Dictionary<string, object>();
params["D1"] = "D1";
params["D2"] = "D2";
params["D3"] = "D3";

int affectedRows  = odp.ParameterizedWrite(sql, params);

if (!String.IsNullOrWhiteSpace(odp.ERROR))
{
    throw new Exception(odp.ERROR);
}

//read
string sql = @"SELECT * FROM TABLE WHERE D1 = :D1";

Dictionary<string, object> params = new Dictionary<string, object>();
params["D1"] = "D1";

DataTable dt = odp.ParameterizedRead(sql, params);
if (!String.IsNullOrWhiteSpace(odp.ERROR))
{
    throw new Exception(odp.ERROR);
}

Notes: you have to change these lines in ODPNetConnect.cs to set connection string:

static private string devConnectionString = "SET YOUR DEV CONNECTION STRING";
static private string productionConnectionString = "SET YOUR PRODUCTION CONNECTION STRING";

And you need to change line 123 to set environment to dev or prod.

public OracleConnection GetConnection(string env = "dev", bool cacheOn = false)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜