请帮助我,我目前陷入了这个错误:
ExecuteNonQuery: Connection property has not been initialized
我阅读了许多相关问题,但没有一个能够奏效。我也在谷歌搜索希望得到答案,但遗憾的是我没有找到任何答案。 :(
这是我的代码。
namespace jollibee4
{
public partial class AccountRegister : Form
{
public AccountRegister()
{
InitializeComponent();
}
private void add_Click(object sender, EventArgs e)
{
try
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = @"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\dbms\jollibee.accdb";
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd = new OleDbCommand("insert into Employee_Details ([username],[password],[Name],[Middle_Name],[Surname],[address],[account_Type],[Mobile_Number],[BirthDate]) values (?,?,?,?,?,?,?,?,?);");
cmd.Parameters.AddWithValue("@username", username.Text);
cmd.Parameters.AddWithValue("@password", password.Text);
cmd.Parameters.AddWithValue("@Name", name.Text);
cmd.Parameters.AddWithValue("@Middle_Name", middlename.Text);
cmd.Parameters.AddWithValue("@Surname", surname.Text);
cmd.Parameters.AddWithValue("@address", address.Text);
cmd.Parameters.AddWithValue("@account_Type", accountType.Text);
cmd.Parameters.AddWithValue("@BirthDate", birthdate.Text);
cmd.Parameters.AddWithValue("@Mobile_Number", mobilenumber.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("done");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
答案 0 :(得分:2)
您正在创建命令两次,导致第二个实例失去连接:
private void add_Click(object sender, EventArgs e)
{
try
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = @"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\dbms\jollibee.accdb";
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
//THIS LINE IS THE PROBLEM
cmd = new OleDbCommand("insert into Employee_Details ([username],[password],[Name],[Middle_Name],[Surname],[address],[account_Type],[Mobile_Number],[BirthDate]) values (?,?,?,?,?,?,?,?,?);");
cmd.Parameters.AddWithValue("@username", username.Text);
cmd.Parameters.AddWithValue("@password", password.Text);
cmd.Parameters.AddWithValue("@Name", name.Text);
cmd.Parameters.AddWithValue("@Middle_Name", middlename.Text);
cmd.Parameters.AddWithValue("@Surname", surname.Text);
cmd.Parameters.AddWithValue("@address", address.Text);
cmd.Parameters.AddWithValue("@account_Type", accountType.Text);
cmd.Parameters.AddWithValue("@BirthDate", birthdate.Text);
cmd.Parameters.AddWithValue("@Mobile_Number", mobilenumber.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("done");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
应该是:
cmd.CommandText = "insert into Employee_Details ([username],[password],[Name],[Middle_Name],[Surname],[address],[account_Type],[Mobile_Number],[BirthDate]) values (?,?,?,?,?,?,?,?,?);"