以下是我的Web应用程序的aspx.cs文件:
protected void Button1_Click(object sender,EventArgs e) {
SqlDataReader myDataReader = null;
string connectionString = "Data Source=[my source];Initial Catalog=[catalog name];Integrated Security=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand returnResults = new SqlCommand("SELECT " + categoryName + " FROM Teacher WHERE " + categoryName + " LIKE '%" + searchText + "%'", connection);
connection.Open();
myDataReader = returnResults.ExecuteReader(CommandBehavior.CloseConnection);
while (myDataReader.Read())
{
Console.Write(myDataReader.GetInt32(0) + "\t");
Console.Write(myDataReader.GetString(2) + " " + myDataReader.GetString(1) + "\t");
Console.Write(myDataReader.GetString(3) + "\t");
if (myDataReader.IsDBNull(4))
Console.Write("N/A\n");
else
Console.Write(myDataReader.GetInt32(4) + "\n");
}
myDataReader.Close();
connection.Close();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
categoryName = DropDownList1.SelectedItem.Value;
}
protected void SearchBox_TextChanged(object sender, EventArgs e)
{
searchText = SearchBox.Text;
}
我的数据库有一个包含大约24列的表。我创建的DropDownList有一个选项可以选择每个列名。下面有一个SearchBox,用户可以在其中输入要搜索的关键字。
我想将DropDownList选项保存为“categoryName”,我想将SearchBox输入保存为“searchText”。当我运行应用程序时,我收到此错误:
描述:执行当前Web请求期间发生了未处理的异常。请查看堆栈跟踪,以获取有关错误及其在代码中的起源位置的更多信息。
异常详细信息:System.Data.SqlClient.SqlException:关键字“FROM”附近的语法不正确。
来源错误: 第48行:myDataReader = returnResults.ExecuteReader(CommandBehavior.CloseConnection);
我不确定如何从这里进步,所以任何帮助都表示赞赏。如果您需要更多信息,请询问。
答案 0 :(得分:2)
这个怎么样:
SqlCommand returnResults = new SqlCommand("SELECT categoryName FROM Teacher WHERE categoryName LIKE '%" + searchText + "%'", connection);
这假设categoryName是您想要返回的列,也是您想要搜索的列。您的原始查询有些错误:使用变量而不是列名,并且未引用LIKE值。
如果要搜索的列是动态的,并通过下拉框选择,并且该值存储在变量categoryName中:
SqlCommand returnResults = new SqlCommand("SELECT " + categoryName + " FROM Teacher WHERE " + categoryName + " LIKE '%" + searchText + "%'", connection);
答案 1 :(得分:0)
看起来你可能缺少空格
"SELECT" + categoryName + "FROM Teacher WHERE" + searchText + " LIKE " + "%" + searchText + "%", connection);
将返回类似
的内容 SELECTmycolumnnameFROM Teacher WHEREmycolumn LIKE %john%
我认为你应该这样做
"SELECT " + categoryName + " FROM Teacher WHERE " + searchText + " LIKE """ + "%" + searchText + "%""", connection);
获取
SELECT mycolumnname FROM Teacher WHERE mycolumn LIKE "%john%"