简体   繁体   English

在C#中执行sql命令时出错

[英]Error while executing a sql command in c#

I am using asp.net with c# and there exist an error in these line of codes. 我在C#中使用asp.net,这些代码行中存在错误。

protected void btnsubmit_Click(object sender, EventArgs e)
{
    string type = "c";
    string FID = Session["FID"].ToString();
    SqlConnection cn = new SqlConnection();
    SqlCommand cmd = new SqlCommand();
    //int str_diff = Convert.ToInt32(ConfigurationManager.AppSettings["Difference"]);
    cn.ConnectionString = @"Data Source=BOPSERVER;Initial Catalog=Project;Integrated Security=True";
    cn.Open();
    cmd.CommandText = "update TrackingFaculty_det SET Type=@Type WHERE (FID=@FID) and DATEDIFF(d,TrackingFaculty_det.LastUpdateDate,GETDATE())>60";
    cmd.Parameters.Add("@FID",SqlDbType.VarChar,10);
    cmd.Parameters["@FID"].Value = FID;
    cmd.Parameters.Add("@Type", SqlDbType.VarChar, 1);
    cmd.Parameters["@Type"].Value = type;
    cmd.ExecuteNonQuery();
    cn.Close();

    Response.Redirect("~/Faculty/Personaldet.aspx");
}

错误!!!

您尚未将连接设置为命令

cmd.Connection = cn;

You need to assign the SqlConnection to the SqlCommand . 您需要将SqlConnection分配给SqlCommand As an additional suggestion I would wrap the connection in a using block to ensure it is correctly disposed in the case of an exception. 作为其他建议,我会将连接包装在using块中,以确保在发生异常的情况下正确处理该连接。

using (SqlConnection cn = new SqlConnection(@"Data Source=BOPSERVER;Initial Catalog=Project;Integrated Security=True") 
{
    cn.Open();
    SqlCommand cmd = new SqlCommand("update TrackingFaculty_det SET Type=@Type WHERE (FID=@FID) and DATEDIFF(d,TrackingFaculty_det.LastUpdateDate,GETDATE())>60", cn);
    cmd.Parameters.Add("@FID",SqlDbType.VarChar,10);
    cmd.Parameters["@FID"].Value = FID;
    cmd.Parameters.Add("@Type", SqlDbType.VarChar, 1);
    cmd.Parameters["@Type"].Value = type;
    cmd.ExecuteNonQuery();
}
    SqlCommand cmd = new SqlCommand("update TrackingFaculty_det SET Type=@Type WHERE (FID=@FID) and DATEDIFF(d,TrackingFaculty_det.LastUpdateDate,GETDATE())>60", cn);
    cmd.Parameters.Add("@FID",SqlDbType.VarChar,10);
    cmd.Parameters["@FID"].Value = FID;
    cmd.Parameters.Add("@Type", SqlDbType.VarChar, 1);
    cmd.Parameters["@Type"].Value = type;
    cmd.ExecuteNonQuery();                       

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM