我正在尝试在我的应用中运行以下查询:
SELECT * FROM jobs jo
INNER JOIN units un ON jo.unitid = un.unitid
INNER JOIN complex co ON un.complexid = co.complexid
WHERE co.complexid = xcomplexid AND jo.status = xstatus
这应该得到一个列表,列出存储在job表中的指定复合体(我总是使用x<column name>
作为我的参数名称,并且它们总能正常工作),它们具有指定的状态集。
现在,如果我通过文本命令(使用System.Data.CommandType.Text)运行它,我会收到以下错误(如果我在数据库上运行查询清理并填入值,则它会起作用):
where子句
中的未知列'xcomplexid'
如果我将此选项复制到存储过程中并使用System.Data.CommandType.StoredProcedure
代替,那么它将起作用。
虽然这显然是我应该做的,但我真的不明白为什么.NET或MySQL实际上迫使我使用SP ......这是我做错了吗?
我的完整代码如下(请注意,其中大约一半尚未经过测试):
private enum FilterType
{
None = 0,
Complex = 1,
DateRange = 2,
Subcontractor = 3,
MultipleSubcontractors = 4
}
private FilterType filter;
private void loadReport()
{
string cmd = String.Empty;
List<MySqlParameter> args = new List<MySqlParameter>();
// xstatus will be used in all Report queries
args.Add(new MySqlParameter("xstatus", MySqlDbType.VarChar));
args[args.Count - 1].Value = ddlStatus.SelectedItem.Value;
// filter has been set previously in execution by actions performed by the user
switch (filter)
{
case FilterType.Complex:
cmd = "select * from jobs jo inner join units un on jo.unitid = un.unitid inner join complex co on un.complexid = co.complexid where co.complexid = xcomplexid and jo.status = xstatus";
args.Add(new MySqlParameter("xcomplexid", MySqlDbType.Int32));
args[args.Count - 1].Value = Convert.ToInt32(ddlComplex.SelectedItem.Value);
break;
// other cases will appear here
}
// Database(string CommandText, System.Data.CommandType CommandType, List<MySqlParameter Parameters)
using (Database db = new Database(cmd, System.Data.CommandType.Text, args))
{
Session["reportData"] = db.GetDataTable();
// db.GetDataTable simply populates a data table
// with the data returned by the query through the
// use of a DataAdapter
gvItems.DataSource = (DataTable)Session["reportData"];
gvItems.DataBind();
}
}
答案 0 :(得分:0)
以text命令运行时,必须向名称为'@xcomplexid'
的命令对象添加一个参数才能使其正常工作。(就像对存储过程一样。)
cmd = "select * from jobs jo inner join units un on jo.unitid = un.unitid inner join complex co on un.complexid = co.complexid where co.complexid = @xcomplexid and jo.status = xstatus";
args.Add(new MySqlParameter("@xcomplexid", MySqlDbType.Int32));
args[args.Count - 1].Value = Convert.ToInt32(ddlComplex.SelectedItem.Value);
break;
答案 1 :(得分:0)
试试这个 -
cmd = "select * from jobs jo inner join units un on jo.unitid = un.unitid inner join complex co on un.complexid = co.complexid where co.complexid = @xcomplexid and jo.status = @xstatus";
args.Add(new MySqlParameter("@xcomplexid", MySqlDbType.Int32));