我哪里做错了?
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请求期间发生了未处理的异常。请查看堆栈跟踪了解更多信息有关错误及其在代码中产生的位置的信息。Exception Details: System。InvalidOperationException: ExecuteNonQuery需要一个打开的可用连接。连接的当前状态是关闭的。
源错误:第31行:command.ExecuteNonQuery();
我试着看一些其他的线程,但没有帮助:
ExecuteNonQuery需要一个打开的可用连接。连接's当前状态为关闭
MS Access DB执行后不保存更改(c#)
您似乎忘记打开连接(并且将错误的连接分配给命令)。试一试:
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语句。它将管理您的连接。
After
OleDbConnection conn = OpenDbConnection();
添加conn.Open();
或者将OpenDbConnection
修改为:
private OleDbConnection OpenDbConnection()
{
string connectionString = GetConnectionString();
OleDbConnection conn = new OleDbConnection {ConnectionString = connectionString};
conn.Open();
return conn;
}