Question

i get this error :Query input must contain at least one table or query my code is:

    using (OleDbConnection myCon = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=timetabledata.accdb")){                       
        OleDbCommand cmd = new OleDbCommand();
        cmd.CommandType = CommandType.Text;
                           string q = "INSERT INTO timehourly (teacherid,subjectid) Values ('@teacherID','@subjid')" + " WHERE hour='@i' AND dayid='@ds'";
                          cmd.Parameters.AddWithValue("@teacherID", Convert.ToInt32(teacher_combo.SelectedValue).ToString());
                           cmd.Parameters.AddWithValue("@subjid",  Convert.ToInt32(subject_combo.SelectedValue).ToString());
                           cmd.Parameters.AddWithValue("@i",i.ToString());
cmd.Parameters.AddWithValue("@ds",ds.Tables[0].Rows[k].ItemArray[0].ToString());
                            cmd.CommandText = q;
        cmd.Connection = myCon;
        myCon.Open();
        cmd.ExecuteNonQuery();
        System.Windows.Forms.MessageBox.Show("successfully added", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);}
Was it helpful?

Solution

You need to remove the apostrophes from your parameter declarations. Also verify that there is data in the values you are passing to the query. Also assign your CommandText before adding the parameters.

Also you can wrap the OleDbCommand in a using statement also as it implementes IDisposable.

Then, you are trying to do an INSERT with a WHERE clause, which will not work.

INSERT statements are meant to actually "insert" a row into the table, you cannot insert a row where there is already a row.

What you are looking for is UPDATE - I have edited the syntax below to reflect this.

using (OleDbConnection myCon = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=timetabledata.accdb"))
using (OleDbCommand cmd = new OleDbCommand())
{                       
    cmd.CommandType = CommandType.Text;
    string q = "UPDATE timehourly SET teacheridh = @teacherId, SET subjectidh = @subjid  WHERE hour=@i AND dayid=@ds";
    cmd.CommandText = q;
    cmd.Parameters.AddWithValue("@teacherID", Convert.ToInt32(teacher_combo.SelectedValue).ToString());
    cmd.Parameters.AddWithValue("@subjid",  Convert.ToInt32(subject_combo.SelectedValue).ToString());
    cmd.Parameters.AddWithValue("@i",i.ToString());
    cmd.Parameters.AddWithValue("@ds",ds.Tables[0].Rows[k].ItemArray[0].ToString());

    cmd.Connection = myCon;
    myCon.Open();
    cmd.ExecuteNonQuery();
    System.Windows.Forms.MessageBox.Show("successfully added", "Caption",        MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
} 

If you really did mean to do an INSERT then just take the WHERE out of your q string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top