[ASP.NET]使用Oracle.ManagedDataAccess的OracleParameter参数化和OracleDataAdapter模糊查询

时间:2023-03-08 18:10:58

今天写个查询员工的信息的demo遇到了2个问题

问题1.使用Oracle.ManagedDataAccess的OracleParameter参数化

OracleParameter 的使用(参数名要以:开头,不允许包含@等特殊字符)

在使用OracleParameters时,CommandText 中的参数要以":"开头,不能包含@等特殊字符。而在其它地方引用到此参数时可以不必加上":",程序会自动为其加上":"

             cmdStr = "select * from sys_user_info where user_no = :userno or user_no = :usernoleave";
pars = new OracleParameter[]{
new OracleParameter("userno",OracleDbType.Varchar2,),
new OracleParameter("usernoleave",OracleDbType.Varchar2,),
};
pars[].Value = TextBox1.Text.Trim();
pars[].Direction = ParameterDirection.InputOutput;
pars[].Value = "#" + TextBox1.Text.Trim() + "#";
pars[].Direction = ParameterDirection.InputOutput;

参考下 OracleParameter 的使用(参数名要以:开头,不允许包含@等特殊字符)

问题2.OracleDataAdapter模糊查询

   cmdStr = "select * from newmes.sys_user_info where user_no like '%'||:usernoleave||'%'";
             cmdStr = "select * from newmes.sys_user_info where user_no like :usernoleave";
pars = new OracleParameter[]{
new OracleParameter("usernoleave",OracleDbType.Varchar2,),
};
pars[].Value = "%"+TextBox1.Text.Trim()+"%";

整个Demo的代码如下:

    protected void Button1_Click(object sender, EventArgs e)
{
string ConnStr = System.Configuration.ConfigurationManager.ConnectionStrings["OracleConnString"].ConnectionString;
string cmdStr = string.Empty;
OracleParameter[] pars;
if (!CheckBox1.Checked)
{
cmdStr = "select * from sys_user_info where user_no = :userno or user_no = :usernoleave";
pars = new OracleParameter[]{
new OracleParameter("userno",OracleDbType.Varchar2,),
new OracleParameter("usernoleave",OracleDbType.Varchar2,),
};
pars[].Value = TextBox1.Text.Trim();
pars[].Direction = ParameterDirection.InputOutput;
pars[].Value = "#" + TextBox1.Text.Trim() + "#";
pars[].Direction = ParameterDirection.InputOutput;
}
else
{
cmdStr = "select * from newmes.sys_user_info where user_no like '%'||:usernoleave||'%'";
pars = new OracleParameter[]{
new OracleParameter("usernoleave",OracleDbType.Varchar2,),
};
pars[].Value = TextBox1.Text.Trim();
pars[].Direction = ParameterDirection.InputOutput;
}
try
{
DataTable ds = new DataTable();
if (TextBox1.Text.Trim().Equals(""))
{
throw new Exception("请输入工号");
}
using (OracleConnection con = new OracleConnection(ConnStr))
{
using (OracleDataAdapter oda = new OracleDataAdapter(cmdStr, con))
{ oda.SelectCommand.Parameters.AddRange(pars);
oda.SelectCommand.CommandType = CommandType.Text;
oda.Fill(ds);
}
}
if (ds.Rows.Count>)
{
lblMessage.Text = ds.Rows.Count+"pcs data";
lblMessage.ForeColor = System.Drawing.Color.Red;
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
{
lblMessage.Text = "No Data";
lblMessage.ForeColor = System.Drawing.Color.Red;
} }
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "');</script>");
GridView1.DataSource = null;
GridView1.DataBind();
lblMessage.Text = "";
}
}