我在这里做错了什么?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