質問

I've searched for my question here, but I couldn't find it. I am using Microsoft VS 2010 C#.

Here is my code:

private OleDbConnection myCon;
public Form5()
{
   myCon = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|ForeignWorkerinfo.accdb");
   InitializeComponent();
}

private void Form5_Load(object sender, EventArgs e)
{
   // TODO: This line of code loads data into the 'foreignWorkerinfoDataSet.FWinFO' table. You can move, or remove it, as needed.
   this.fWinFOTableAdapter.Fill(this.foreignWorkerinfoDataSet.FWinFO);
}

private void button1_Click(object sender, EventArgs e)
{                
   OleDbCommand cmd = new OleDbCommand();
   cmd.Connection = myCon;
   cmd = new OleDbCommand("INSERT INTO [FWinFO] ([ID], [Name], [Gender], [Date of Birth], [Country], [Date of Expire], [Passport No], [Working Place]) VALUES (?, ?, ?, ?, ?, ?, ?, ?);");

   cmd.Parameters.AddWithValue("@id", textBox8.Text);
   cmd.Parameters.AddWithValue("@name", textBox1.Text);
   cmd.Parameters.AddWithValue("@gender", textBox2.Text);
   cmd.Parameters.AddWithValue("@dob", dateTimePicker1.Value);
   cmd.Parameters.AddWithValue("@country", textBox4.Text);
   cmd.Parameters.AddWithValue("@doe", dateTimePicker2.Value);
   cmd.Parameters.AddWithValue("@passport", textBox6.Text);
   cmd.Parameters.AddWithValue("@workplace", textBox7.Text);

   cmd.ExecuteNonQuery();
   myCon.Close();
}

Can anyone tell me why the connection property has not been initialized?

役に立ちましたか?

解決 2

Try opening the connection first, with myCon.Open()

他のヒント

You have two errors, the one you state, and one that will occur after you fix the first one:

The first one is that you are overwriting your setting of the Connection property on the cmd by calling new again. Either do one new, or set the query text property.

The next error is:

You have to call myCon.Open to make the ExecuteNonQuery() call. You cannot execute a query against an unopened connection.

You can always check if the connection is open by checking its State to see if it is Open.

However, I would actually suggest to create the connection on demand, but it depends on the code. Using a global, shared connection object leaves itself open to problems. You can cache the connection string, though.

OleDbCommand cmd = new OleDbCommand();
cmd.Connection = myCon;
cmd = new OleDbCommand("INSERT INTO [FWinFO] ([ID], [Name], [Gender], [Date of Birth], [Country], [Date of Expire], [Passport No], [Working Place]) VALUES (?, ?, ?, ?, ?, ?, ?, ?);");

The above code is correct. The problem is, you aren't opening the connection. Please use:

 OleDbCommand cmd = new OleDbCommand();
 cmd.Connection = myCon;
 myCon.Open();
 cmd = new OleDbCommand("INSERT INTO [FWinFO] ([ID], [Name], [Gender], [Date of Birth], [Country], [Date of Expire], [Passport No], [Working Place]) VALUES (?, ?, ?, ?, ?, ?, ?, ?);");
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top