我正在c#中使用此代码来更新我的表:
public static int updateMytable(string accessCode, string response)
{
OracleConnection conn = DB.GetConnection();
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "update mytable set response_id= :p_response , response_date=sysdate where access_code = :p_access_code";
cmd.Parameters.Add("p_access_code", accessCode);
cmd.Parameters.Add("p_response", response);
cmd.CommandType = CommandType.Text;
int res = cmd.ExecuteNonQuery();
conn.Close();
return res;
}
access_code是varchar2
当我删除条件“ where”时,它将更新所有内容。 当我使用字符串命令而不是绑定变量时,它也可以正常工作。
string str = "update mytable set response_id= "+response+" , response_date=sysdate where access_code = "+accessCode;
你能建议吗?
答案 0 :(得分:1)
添加cmd.BindByName = true;
以便通过变量(:p_response
,:p_access_code
)的名称而不是 position 来绑定变量:>
public static int updateMytable(string accessCode, string response) {
if (string.IsNullOrEmpty(accessCode))
return 0;
using (OracleConnection conn = DB.GetConnection()) {
conn.Open();
using (OracleCommand cmd = new OracleCommand()) {
// When binding varaibles, use their names, not positions
cmd.BindByName = true;
cmd.Connection = conn;
cmd.CommandText =
@"update mytable
set response_id = :p_response,
response_date = sysdate
where access_code = :p_access_code";
cmd.Parameters.Add(":p_response", OracleDbType.Varchar2);
cmd.Parameters.Add(":p_access_code", OracleDbType.Varchar2);
cmd.Parameters[":p_response"].Value = string.IsNullOrEmpty(response)
? (object) (DBNull.Value)
: response;
cmd.Parameters[":p_access_code"].Value = accessCode;
return cmd.ExecuteNonQuery();
}
}
}