Search code examples
c#winformsoledb

Adding data in the database using microsoft access


I really can't add any data in my database, I can read what's on the DB but can't write, I've tried many codes but didn't work :( I ended up with this code,

private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string user = textBox1.Text;
                string pass = textBox2.Text;

                string myExecutequery = "INSERT INTO Accountstbl (Username,Password) VALUES (@user,@pass)";
                OleDbCommand cmd = new OleDbCommand(myExecutequery, con);
                cmd.Connection.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

the error says that:

System.Data.OleDb.OleDbException: Syntax error in INSERT INTO statement.
   at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr)
   at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)
   at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
   at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult)
   at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
   at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
   at VirginiTEAcorp.Form3.button1_Click(Object sender, EventArgs e) in C:\Documents and Settings\12-014s\My Documents\applications\Database\WindowsFormsApplication1\Form3.cs:line 31

someone help me pls :(


Solution

  • string myExecutequery = "INSERT INTO Accountstbl (Username,Password) VALUES 
    (@user,@pass)";
    
    con.Open();
    
    try
    {
     OleDbCommand cmd = new OleDbCommand(myExecutequery, con);
     cmd.Parameters.Add("@user", user);
     cmd.Parameters.Add("@pass", pass);     
     cmd.ExecuteNonQuery();
     cmd.Dispose();
     cmd = null;
    }
    catch(Exception ex)
    {
      throw new Exception(ex.ToString(), ex);
    }
    finally
    {
     con.Close();
    }
    

    OR

    Your query should be like this

    string myExecutequery = "INSERT INTO Accountstbl (Username,Password) VALUES 
    ('"+ user +"','"+ pass +"')";
    

    And you need to open the connection before it is adding to oleDBCommand like

    con.Open();