Mysql 查询在作为文本传递到 db 时会引发错误,但用作存储过程
本文关键字:错误 存储过程 db 查询 文本 Mysql | 更新日期: 2023-09-27 18:31:31
我正在尝试在我的应用程序中运行以下查询:
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
这应该获取存储在具有指定状态集的指定复合体(我总是使用 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();
}
}
作为文本命令运行时,必须向命令对象添加一个参数,名称为 '@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;
试试这个-
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));