我在这里做错了什么?
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
请您参考如下方法:
您似乎忘记打开连接(并为命令分配了错误的连接)。尝试:
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 语句。它将为您管理您的连接。关闭。
