我在這裏做錯了什麼?OleDbConnection - ExecuteNonQuery需要一個開放且可用的Connection。連接的當前狀態已關閉
using System.Data;
using System.Data.OleDb;
namespace myProject.Account
{
public class DbManager
{
private OleDbConnection OpenDbConnection()
{
string connectionString = GetConnectionString();
return new OleDbConnection {ConnectionString = connectionString};
}
private string GetConnectionString()
{
return "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\myDataBase.accdb";
}
public void InsertUser(string name, string loginName, string password)
{
OleDbConnection conn = OpenDbConnection();
OleDbCommand command = new OleDbCommand(
"INSERT INTO tblUser (UserName, LoginName, Password) VALUES (@name,@login,@pwd)",
Conn);
command.Parameters.Add("@name", OleDbType.VarChar).Value = name;
command.Parameters.Add("@login", OleDbType.VarChar).Value = loginName;
command.Parameters.Add("@pwd", OleDbType.VarChar).Value = password;
command.ExecuteNonQuery();
}
}
}
。
我得到這個錯誤:
ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.Exception Details: System.InvalidOperationException: ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.
Source Error:
Line 31: command.ExecuteNonQuery();
我也想看看一些其他的線程,但沒有幫助:
ExecuteNonQuery requires an open and available Connection. The connection's current state is closed
MS Access DB doesnt save changes after execution (C#)
我建議將連接放置在'using'塊中以釋放資源。 –
當我真的只創建數據庫連接時,調用一個方法'OpenDbConnection'似乎非常「危險」,但是**實際上並沒有**打開它!種類違背了「最少驚喜的原則」....要麼實際**打開**在該方法中的連接,或稱之爲「CreateDbConnection」或什麼.... –
謝謝Uwe凱姆 - 我很新C#對於其他人感興趣,爲什麼使用「使用」看到線程:http://stackoverflow.com/questions/75401/uses-of-using-in-c-sharp – Jedi