如何在asp.net中编写选择参数化查询

如何在asp.net中编写选择参数化查询,asp.net,visual-studio,Asp.net,Visual Studio,下面的代码是为了在asp.net中调用参数化的select查询而编写的 public bool checkConflictTime() { bool TimeExists = false; DataSet ds = new DataSet(); SqlConnection sqlconn = new SqlConnection(); sqlconn.ConnectionString = ConfigurationManager.ConnectionString

下面的代码是为了在asp.net中调用参数化的select查询而编写的

public bool checkConflictTime()
{
    bool TimeExists = false;

    DataSet ds = new DataSet();

    SqlConnection sqlconn = new SqlConnection();
    sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["TestConn"].ConnectionString;
    string sql = @"SELECT * FROM Images WHERE starttime= @starttime AND endtime = @endtime";

    SqlCommand sqlcommand = new SqlCommand(sql,sqlconn);

    //sqlcommand.Connection = sqlconn;

    //string sql = "CheckConflictTimings";


    sqlcommand.CommandType = CommandType.Text;
    sqlcommand.CommandText = sql;

    sqlcommand.Parameters.Add(new SqlParameter("@starttime", ddlStartTime.SelectedItem.Text));
    sqlcommand.Parameters.Add(new SqlParameter("@endtime", ddlEndTime.SelectedItem.Text));

    SqlDataAdapter da = new SqlDataAdapter(sql, sqlconn);
    try
    {
        da.Fill(ds);
        if (ds.Tables[0].Rows.Count > 0)
        {
            TimeExists = true;
        }
    }   
    catch (Exception ex)
    {

    }
    finally
    {
        sqlconn.Close();
        sqlconn.Dispose();  
    }
    return TimeExists;
}
有什么不对劲吗?它抛出错误:必须声明标量变量“@starttime” 填充数据适配器时

试试看

sqlcommand.Parameters.Add(new SqlParameter("starttime", ddlStartTime.SelectedItem.Text));

添加参数时,我认为您不需要
@
前缀。

我认为您没有将命令作为SelectCommand传递给适配器

da.SelectCommand = sqlcommand;
试一试

试一试

而不是

   sqlcommand.Parameters.Add(new SqlParameter("@starttime", ddlStartTime.SelectedItem.Text));

在发布问题之前,请尝试此选项。不luck@Xor我认为查询的结构可以更好地形成,看看这个例子,也许可以应用它的格式,这应该会使开发更容易
  sqlcommand.Parameters.AddWithValue("@starttime",ddlStartTime.SelectedItem.Text);
   sqlcommand.Parameters.Add(new SqlParameter("@starttime", ddlStartTime.SelectedItem.Text));