问题
I am trying to create a prepared statement in c#.
For some reason everything I try ends up with an exeption.
This is my code for now:
using (OracleCommand cmd = new OracleCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into daily_cdr_logs " +
"(message) " +
"values " +
"(:message)";
cmd.Parameters.Add(:message, msg);
//OracleDbType.Int32, postpaid_duration, ParameterDirection.Input);
cmd.Prepare();
cmd.ExecuteNonQuery();
}
I am getting exeption: "Operation is not valid due to the current state of the object."
回答1:
A typical Oracle prepared statement looks like this.
(notice that only the definition in the prepared statement has the : colon, and the one in the cmd.Parameters.AddWithValue call does not)
String msg = "something here";
using (OracleConnection con = new OracleConnection(...insert connection params here...))
{
con.Open();
OracleCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = @"
insert into daily_cdr_logs
(message)
values
(:message)";
cmd.Parameters.AddWithValue("message", msg);
cmd.ExecuteNonQuery();
}
回答2:
I would suggest doing it like this:
//create a connection
string conString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString;
OracleConnection con = new OracleConnection(conString);
//create SQL and insert parameters
OracleCommand cmd = new OracleCommand("insert into daily_cdr_logs (message) values (:_message)", con);
cmd.Parameters.Add(new OracleParameter("_message", msg));
try
{
//if connection is closed, open it
if (con.State == ConnectionState.Closed)
con.Open();
//execute query
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
//do something with the error
}
finally
{
//if connection is open, close it
if (con.State == ConnectionState.Open)
con.Close();
}
I have created my connection string in my web.config file, demonstrated here.
来源:https://stackoverflow.com/questions/17921492/c-sharp-equivalent-to-java-prepared-statement