我在这里做错了什么?
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需要一个开放且可用的连接。连接的当前状态已关闭 描述:执行当前Web请求期间发生未处理的异常。请查看堆栈跟踪了解更多信息 有关错误的信息以及它在代码中的起源。
异常详细信息:System.InvalidOperationException:ExecuteNonQuery需要一个开放且可用的连接。连接的当前状态已关闭。
来源错误:
第31行:command.ExecuteNonQuery();
我试图看一些其他线程,但没有人帮助过:
ExecuteNonQuery requires an open and available Connection. The connection's current state is closed
答案 0 :(得分:2)
在
OleDbConnection conn = OpenDbConnection();
添加
conn.Open();
或者,修改OpenDbConnection
,如下所示:
private OleDbConnection OpenDbConnection()
{
string connectionString = GetConnectionString();
OleDbConnection conn = new OleDbConnection {ConnectionString = connectionString};
conn.Open();
return conn;
}
答案 1 :(得分:2)
您似乎忘记打开连接(并且正在为命令分配错误的连接)。尝试:
using(OleDbConnection conn = OpenDbConnection())
{
using(OleDbCommand command = new OleDbCommand(
"INSERT INTO tblUser (UserName, LoginName, Password) VALUES (@name,@login,@pwd)"))
{
command.CommandType = CommandType.Text;
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.Connection = conn;
conn.Open();
command.ExecuteNonQuery();
}
}
相反。我也建议使用using语句。它将为您管理您的connection.close。