【问题标题】:Unable to update database with the Window Form Application无法使用窗口窗体应用程序更新数据库
【发布时间】:2016-03-31 13:55:38
【问题描述】:

我正在尝试使用我创建的窗口窗体更新我的数据库,但是当我执行代码时发生错误:

“System.InvalidOperationException”类型的未处理异常 发生在 System.Data.dll" at comm.ExecuteNonQuery();

这是我用来连接数据库的代码。是不是我更新数据库的代码错了?

string conn=ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
SqlConnection connection = new SqlConnection(conn);
SqlCommand comm = new SqlCommand("UPDATE ExerciseInstruction SET Accumulated_Daily_Sets_Completed = '0' WHERE ExerciseInstructionsID ='" + exerciseInstructionID +"'", connection);
comm.ExecuteNonQuery();

这是完整的错误信息:

ExecuteNonQuery 需要一个开放且可用的连接。这 连接的当前状态为关闭。

【问题讨论】:

  • 请写下你所有的异常信息。 InnerException 属性中还有其他更详细的信息
  • 你应该先打开connection

标签: asp.net winforms


【解决方案1】:

错误信息说明一切。如果代码不知道如何访问数据库,则无法执行该命令。只需致电connection.Open 即可解决问题,但我认为您需要使用正确的方法来执行查询。

这称为参数化查询。通过这种方式,您不会将字符串连接在一起以形成查询文本,而是使用参数将值传递给数据库引擎和包含参数占位符的特殊格式化字符串。

这样做有两个主要优点。无法使用 Sql Injection hack 来定位您的代码,并且您不必处理字符串周围的引用(错误的无限来源)

string conn=ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;

string cmdText = @"UPDATE ExerciseInstruction 
   SET Accumulated_Daily_Sets_Completed = 0 
   WHERE ExerciseInstructionsID =@exid";
using(SqlConnection connection = new SqlConnection(conn))
using(SqlCommand comm = new SqlCommand(cmdText, connection))
{
    connection.Open(); // Need this before executing the query
    comm.Parameters.Add("@exid", SqlDbType.Int).Value =  exerciseInstructionID;
    comm.ExecuteNonQuery();
}

【讨论】:

    猜你喜欢
    • 2021-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-08
    • 1970-01-01
    • 2011-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多