作为停止使用动态SQL生成并鼓励使用绑定变量的努力的一部分,我遇到了一些问题。
我正在使用Oracle Data Providers for .NET从ASP.NET页面查询Oracle 9i数据库
查询
sql = "SELECT somedata FROM sometable WHERE machine = :machineName ";
我将Oracle参数定义如下
OracleParameter parameter = new OracleParameter();
parameter.ParameterName = "machineName";
parameter.OracleDbType = OracleDbType.Varchar2;
parameter.Value = machine; //machine is a variable of type string
parameterList.Add(parameter);
这适用于“=”运算符。但我似乎无法让它与“喜欢”一起工作。我不知道如何格式化查询,以便它接受“%”通配符的使用。
我试过了:
sql = "SELECT somedata FROM sometable WHERE machine LIKE :machineName% ";
sql = "SELECT somedata FROM sometable WHERE machine LIKE ':machineName%' ";
sql = "SELECT somedata FROM sometable WHERE machine LIKE :machineName||% ";
还有:
parameter.Value = machine+'%';
但我得到的是ORA-00911(非法字符)和ORA-01036(非法名称/值)例外。
我做错了什么?
答案 0 :(得分:25)
尝试:
sql = "SELECT somedata FROM sometable WHERE machine LIKE :machineName || '%' ";
由于BIND变量,它周围不需要单引号。但%不是,所以我希望它需要封装。
答案 1 :(得分:0)
这是一个完整的查询示例:
string commandText = "SELECT LastName, FirstName FROM PEOPLE WHERE UPPER(LastName) LIKE '%' || :lastName || '%' AND UPPER(FirstName) LIKE '%' || :firstName || '%'";
string oradb = "yourDatabaseConnectionStringHere"; // Might want to add Using statement for this code and try catch
OracleConnection conn = new OracleConnection(oradb); // C#
conn.Open();
OracleCommand cmd = new OracleCommand
{
Connection = conn,
CommandText = commandText,
CommandType = CommandType.Text
};
/*IMPORTANT: adding parameters must be in order how they are in order in the SQL statement*/
cmd.Parameters.Add(new OracleParameter("lastName", model.LastName.Trim().ToUpper()));
cmd.Parameters.Add(new OracleParameter("firstName", model.FirstName.Trim().ToUpper()));
OracleDataReader dr = cmd.ExecuteReader();