错误 ExecuteNonQuery:连接 属性 尚未初始化 C# (Access)

Error ExecuteNonQuery: Connection property has not been initialized C# (Access)

我有一些这样的代码:

var queryIns = "...";

try
{
    var rowInsert = u.insert(queryIns);
}
catch (Exception)
{
    var msg = "Error";
    MessageBox.Show(msg,...);
}

我的命令是:

public int Command(string queryCommand)
{
    using var conn = openConnection(); //private method that returns the connection with connection string
    using OleDbCommand cmd = getCommand(queryCommand, conn); //private method that returns the command with connection and query
    return cmd.ExecuteNonQuery();
}

最后是这些方法:

private OleDbCommand getCommand(string queryString, OleDbConnection conn)
{
    using var cmd = new OleDbCommand(queryString, conn);
    return cmd;
}

private OleDbConnection openConnection()
{
    using var conn= new OleDbConnection(connString);
    conn.Open();
    return conn;
}

问题是这一切都会抛出异常

ExecuteNonQuery: Connection property has not been initialized

有人可以帮我吗T_T?

Using 将关闭您使用 using、connection、command、httprequest 等使用的所有内容

 using (var conn= new OleDbConnection(connString)) {
       using (var cmd = new OleDbCommand(queryString, conn)) {
              conn.Open();
               return cmd.ExecuteNonQuery();
        } //private method that returns the command with connection and query
  }; //private method that returns the connection with connection string
   
   

您使用disposed(关闭并释放所有资源)连接:

private OleDbConnection openConnection()
{
    // you create the connection
    using var conn= new OleDbConnection(connString); 
    conn.Open();
    return conn;
}                                                    // <- and here you dispose it 

Command 完全相同的问题:cmd 你 return 已处理。

private OleDbCommand getCommand(string queryString, OleDbConnection conn)
{
    using var cmd = new OleDbCommand(queryString, conn); // <- command created 
    return cmd;
}                                                        // <- and disposed

您可以在两种方法中删除 using

private OleDbConnection openConnection()
{
    // we create connection
    conn = new OleDbConnection(connString); 

    try { 
      // try it to open  
      conn.Open(); 
      // return opened (and not disposed!) connection
      return conn;
    }
    catch {
      // on open failure we dispose conenction (to prevent resources leakage) 
      conn.Dispose();
      // and rethrow the exception (to know the exact problem)
      throw; 
    }
} 

// Here we just return a command
private OleDbCommand getCommand(string queryString, OleDbConnection conn) =>
  new OleDbCommand(queryString, conn);

或者可以将方法合并为一个:

public int Command(string queryCommand) 
{
  using var conn = new OleDbConnection(connString); 
  conn.Open();

  using var cmd = new OleDbCommand(queryString, conn);

  return cmd.ExecuteNonQuery();
} // here both conn and cmd will be disposed