当点击搜索按钮时,它会给我这个错误(' 43'附近的语法不正确)43是区域ID,我确保所有表中的区域ID都相同,并且gov id是相同的这也是我使用的代码
protected void Button1_Click(object sender, EventArgs e)
{
//Page.RegisterStartupScript("open", "<script language=javascript>alert('dd')</script>");
// Session["conection"] = "Data Source=MEDICONSULT;Initial Catalog=test;Integrated Security=True";
Session["conection"] = "Data Source=MEDICONSULT;Initial Catalog=test1;Integrated Security=True";
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString);
connection.Open();
SqlCommand command = new SqlCommand();
connection = new SqlConnection((string) Session["conection"]);
connection.Open();
SqlDataAdapter da_1 = new SqlDataAdapter(command);
da_1 = new SqlDataAdapter();
command = new SqlCommand();
command.Connection = connection;
string sql1 = "select Address1,provname from sites where cat_id=2";
if (addressTextBox.Text != "")
{
sql1 = "SELECT provname,address1,LAT,LONG FROM site where cat_id=2 and provname like '%'+@provname+'%'";
SqlParameter search = new SqlParameter();
search.ParameterName = "@provname";
search.Value = addressTextBox.Text.Trim();
command.Parameters.Add(search);
}
if (DropDownList1.SelectedValue != "0")
{
sql1 = " SELECT area, address1, provname FROM sites WHERE cat_id=2 and gov_id='" + DropDownList1.SelectedValue + "'";
}
if (DropDownList2.SelectedValue != "0" && DropDownList1.SelectedValue != "0")
{
sql1 = "SELECT area, address1,provname FROM sites WHERE cat_id=2 and gov_id='" + DropDownList1.SelectedValue + "and area_id='" + DropDownList2.SelectedValue;
}
command.CommandText = sql1;
da_1.SelectCommand = command;
ds_1 = new DataSet();
da_1.Fill(ds_1, "sites");
searchResults.DataSource = ds_1;
searchResults.DataBind();
Label1.Text = ds_1.Tables[0].Rows.Count > 0 ? ds_1.Tables[0].Rows.Count.ToString() : "لا يوجد نتائج من البحث الذي ادخلته";
}
答案 0 :(得分:1)
您在'
之前和查询中错过了单引号and
。
sql1 = "SELECT area, address1,provname FROM sites WHERE cat_id=2 and gov_id='" + DropDownList1.SelectedValue + "'"+ " and area_id='" + DropDownList2.SelectedValue+"'";
但我肯定会说请使用参数化查询。
Sql1 = "SELECT area, address1,provname FROM sites WHERE cat_id=2 and gov_id= @gov_id and area_id= @area_id";
SqlCommand cmd = new SqlCommand(sql1, conn);
cmd.Parameters.AddWithValue("@gov_id", DropDownList1.SelectedValue);
cmd.Parameters.AddWithValue("@area_id", DropDownList2.SelectedValue);
答案 1 :(得分:1)
您应该使用parameterized queries代替。
这种字符串连接对 SQL Injection 攻击是开放的。最常见的是,你可以在这种连接中忘记一些单引号('
)并找到你忘记这些引号的地方真的很难。
sql1 = "SELECT area, address1,provname FROM sites WHERE cat_id=2 and gov_id= @gov and area_id= @area_id";
SqlCommand cmd = new SqlCommand(sql1, conn);
cmd.Parameters.AddWithValue("@gov", DropDownList1.SelectedValue);
cmd.Parameters.AddWithValue("@area_id", DropDownList2.SelectedValue);