我嘗試使用Visual C#學習一些編碼。我創建了一個用於添加和更新Access數據庫的表單。無法從C#.NET更新Access數據庫文件
我可以成功添加到Access文件,但我無法更新它們。
我寫的代碼在網上搜索一些下面相似,但我得到這個錯誤:
ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.
我的代碼是:
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 [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected] WHERE [email protected]";
//string query = "UPDATE aspnet_Users SET [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected] WHERE [email protected]";
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
謝謝Sudhakar! – user3346389
@ user3346389:現在工作嗎? –
現在它給我一個在其他地方聲明的錯誤! – user3346389