簡體   English   中英

關鍵字“選擇”附近的語法不正確。 如何在此代碼中解決

[英]Incorrect syntax near the keyword 'Select'. how to resolve in this code

這段代碼在下面標記的行上引發了錯誤,有人可以指出正確的方向為什么引發錯誤嗎?

 SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString);
    SqlDataAdapter dadapter;
    DataSet dset; 
    string sql = "SELECT * from  SocoetyMaintan";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            dadapter = new SqlDataAdapter(sql, con);
            dset = new DataSet();
            dadapter.Fill(dset);
            DropDownList1.DataSource = dset.Tables[0];
            DropDownList1.DataTextField = "FullName";
            DropDownList1.DataValueField = "Id";
            DropDownList1.DataBind();
            GridViewBind();
        }
    }
      protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            GridViewBind();
        }
        public void GridViewBind()
        {
            dadapter = new SqlDataAdapter("SELECT * from SocoetyMaintan where Id=" + DropDownList1.SelectedValue + "", con);
            dset = new DataSet(); //Throwing Error Here
            dadapter.Fill(dset);
            GridView1.DataSource = dset.Tables[0];
            GridView1.DataBind();

在這里,您忘記了將DropDownList1.SelectedValue轉換為字符串或int數據庫中的任何內容。 因此,請按照以下步驟進行操作。 例如,

dadapter = new SqlDataAdapter("select * from SocoetyMaintan where Id='" + DropDownList1.SelectedValue.ToString() + "';", con);

它認為您缺少Id=引號。

 $"SELECT * from SocoetyMaintan where Id='{DropDownList1.SelectedValue}';"

BTW。 您絕對不應允許用戶直接輸入查詢。 查找“ SQL注入”。

您的書寫方式可能會出錯。 嘗試以下

方法1:

SqlDataAdapter dadapter = new SqlDataAdapter(string.Format("SELECT * FROM SocoetyMaintan WHERE Id = '{0}'",DropDownList1.SelectedValue), con);

方法2 :(首選)

using (SqlDataAdapter dadapter = new SqlDataAdapter("SELECT * FROM SocoetyMaintan WHERE Id = @id", con))
{
    int filter = ID;
    dadapter.SelectCommand.Parameters.AddWithValue("@id", DropDownList1.SelectedValue);
}

1)只需嘗試更改您的查詢,如下所示

dadapter = new SqlDataAdapter("SELECT * from SocoetyMaintan where Id='" + DropDownList1.SelectedValue + "'", con);

注意:最好在查詢中使用准備好的語句。

dadapter = new SqlDataAdapter("SELECT * from SocoetyMaintan where Id=@Id", con);
dadapter.SelectCommand.Parameters.AddWithValue("@Id", DropDownList1.SelectedValue);

2)嘗試設置您的asp:GridView => DataSourceID="GridDataSource"asp:SqlDataSource => ID="GridDataSource"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM