【发布时间】:2021-07-21 21:08:41
【问题描述】:
目前我正在尝试保留一个持久的 where 子句,然后通过附加是否存在每个文本框来附加额外的过滤器。问题是这给了我一个很好的命令,但是在尝试使用该命令时我仍然收到错误。如果有任何简化或指导,将不胜感激!
if (string.IsNullOrEmpty(make) && (string.IsNullOrEmpty(model)) && (string.IsNullOrEmpty(color)) && (string.IsNullOrEmpty(min)) && (string.IsNullOrEmpty(max)) && (string.IsNullOrEmpty(miles)))
{
SqlCommand updateDataGridViewCmd = new SqlCommand("select m.make, m.model, car.price, color.color, car.mileage, carlot.lotid, car.pic from car join makemodel as m ON m.mmid = car.mmid join color ON car.colorid = color.colorid join carlot ON carlot.carid = car.carid; ", sqlCon);
dt.Load(updateDataGridViewCmd.ExecuteReader());
dataGridView1.DataSource = dt;
}
else
{
StringBuilder sqlCommandText = new StringBuilder();
sqlCommandText.Append("select m.make, m.model, car.price, color.color, car.mileage, carlot.lotid, car.pic from car join makemodel as m ON m.mmid = car.mmid join color ON car.colorid = color.colorid join carlot ON carlot.carid = car.carid where");
string CommandText = sqlCommandText.ToString();
SqlCommand updateDataGridViewCmd = new SqlCommand(CommandText, sqlCon);
updateDataGridViewCmd.Parameters.AddWithValue("@make", make);
updateDataGridViewCmd.Parameters.AddWithValue("@model", model);
updateDataGridViewCmd.Parameters.AddWithValue("@min", min);
updateDataGridViewCmd.Parameters.AddWithValue("@max", max);
updateDataGridViewCmd.Parameters.AddWithValue("@mileage", miles);
updateDataGridViewCmd.Parameters.AddWithValue("@color", color);
if (!string.IsNullOrEmpty(make))
{
sqlCommandText.Append(" m.make = @make");
CommandText = sqlCommandText.ToString();
}
if (!string.IsNullOrEmpty(model))
{
sqlCommandText.Append(" OR m.model = @model");
CommandText = sqlCommandText.ToString();
}
if (!string.IsNullOrEmpty(min))
{
sqlCommandText.Append(" car.price between @min");
CommandText = sqlCommandText.ToString();
if (!string.IsNullOrEmpty(max))
{
sqlCommandText.Append(" AND @max");
CommandText = sqlCommandText.ToString();
}
else
{
sqlCommandText.Append(",");
CommandText = sqlCommandText.ToString();
}
}
if (!string.IsNullOrEmpty(color))
{
sqlCommandText.Append(" color.color = @color,");
CommandText = sqlCommandText.ToString();
}
if (!string.IsNullOrEmpty(miles))
{
sqlCommandText.Append(" car.price <= @mileage");
CommandText = sqlCommandText.ToString();
}
sqlCommandText.Append(";");
CommandText = sqlCommandText.ToString();
dt.Load(updateDataGridViewCmd.ExecuteReader());
dataGridView1.DataSource = dt;
}
}
}
【问题讨论】:
-
这里可以使用任何 ORM 吗?在处理动态查询时会有很大帮助
-
什么错误?请添加更多信息,否则只是一个猜谜游戏
-
可能是因为您没有使用
and, or之一链接条件 -
您生成的 SQL 存在大量语法错误。在调试器中看一下
-
命令是什么?