gpt4 book ai didi

c# - OleDbConnection - ExecuteNonQuery 需要一个打开且可用的连接。连接的当前状态是关闭的

转载 作者:太空宇宙 更新时间:2023-11-03 22:06:11 27 4
gpt4 key购买 nike

我在这里做错了什么?

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(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 语句。它将为您管理您的连接。关闭。

关于c# - OleDbConnection - ExecuteNonQuery 需要一个打开且可用的连接。连接的当前状态是关闭的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8371073/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com