我尝试用Visual C#学习一些编码。我创建了一个表单来添加和更新Access数据库。
我可以成功添加到Access文件,但我无法更新它们。
我通过互联网上的一些搜索编写了类似下面的代码,但是我收到了这个错误:
ExecuteNonQuery需要一个开放且可用的连接。连接的当前状态已关闭。
我的代码是:
public partial class form1 : Form
{
private OleDbConnection con;
private void btnUpDate_Click(object sender, EventArgs e)
{
string FirstName = txtFirstName.Text;
string Family = txtFamily.Text;
string City = txtCity.Text;
string approve = txtapprove.Text;
string OfficeNumber = txtOfficeNumber.Text;
string OfficialDossier = txtOfficialDossier.Text;
string Department = txtDepartment.Text;
string Organization = txtOrganization.Text;
OleDbConnection oleDBConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Data Source=F:\\Database.accdb");
string query = "UPDATE Sheet1 SET FirstName=@FirstName, Family=@Family, City=@City, approve=@approve, OfficeNumber=@OfficeNumber, OfficialDossier=@OfficialDossier, Department=@Department, Organization=@Organization WHERE OfficeNumber=@OfficeNumber";
//string query = "UPDATE aspnet_Users SET FirstName=@FirstName, Family=@Family, City=@City, approve=@approve, OfficeNumber=@OfficeNumber, OfficialDossier=@OfficialDossier, Department=@Department WHERE OfficeNumber=@OfficeNumber";
OleDbCommand cmd = new OleDbCommand(query, oleDBConn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@OfficeNumber", OfficeNumber);
cmd.Parameters.AddWithValue("@OfficialDossier", OfficialDossier);
cmd.Parameters.AddWithValue("@FirstName", FirstName);
cmd.Parameters.AddWithValue("@Family", Family);
cmd.Parameters.AddWithValue("@City", City);
cmd.Parameters.AddWithValue("@approve", approve);
cmd.Parameters.AddWithValue("@Department", Department);
cmd.Parameters.AddWithValue("@Organization", Organization);
try
{
con.Open();
int result = cmd.ExecuteNonQuery();
if (result > 0)
MessageBox.Show("Success!");
else
MessageBox.Show("Sorry!");
}
catch (OleDbException)
{
MessageBox.Show("There is a problem!");
}
finally
{
con.Close();
}
}
}
我哪里有错?我不使用DataSet和DataAdapter。那是问题吗?
我正在使用VS 2010
答案 0 :(得分:4)
问题1:您尚未打开分配给oleDBConn
对象的连接对象OleDbCommand
。
您已将oleDBConn
分配给OleDbCommand对象,如下所示:
OleDbCommand cmd = new OleDbCommand(query, oleDBConn);//here you have assigned oleDbConn
但您已打开不同的ConnectionObject con
,如下所示:
con.Open();
解决方案1:
替换它:您应该始终打开分配给OleDbConnection
对象的OleDbCOmmand
(oleDBConn)对象。
con.Open();
有了这个:
oleDBConn.Open();
问题2:您已经创建了一个额外的连接对象con
(在您的btnUpDate_Click
函数之上)并且您错误地使用了相同的连接对象。(打开和关闭错误的连接对象而不是正确的连接对象
解决方案2:删除在btnUpDate_Click
函数顶部创建的额外连接对象,并用con
替换所有oleDBConn
次出现。
完整代码:
try
{
oleDBConn.Open();
int result = cmd.ExecuteNonQuery();
if (result > 0)
MessageBox.Show("Success!");
else
MessageBox.Show("Sorry!");
}
catch (OleDbException ex)
{
MessageBox.Show("There is a problem!"+ex.ToString());
}
finally
{
oleDBConn.Close();
}