Search code examples
c#insertoledb

inserting new data into access


I'd like to insert a new row of data into my oledb. I simply structured my codes the way I did with UPDATE. However, there's error with OleDbCommand ins = new OleDbCommand(insertString, strOleDbConnectionString);

How does it actually work without using tableadapters or parameters etc?

        string strOleDbConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Project.mdb";
        OleDbConnection objConnection = new OleDbConnection(strOleDbConnectionString);

        string insertString = "INSERT INTO jiahe ([Tag ID], User, Age, [Phone Number]) VALUES (123, Esther, 19, 92786618)";
        string newTagID = textBox1.Text;
        string newUser = textBox2.Text;
        string newAge = textBox3.Text;
        string newPhoneNumber = textBox4.Text;

        OleDbCommand ins = new OleDbCommand(insertString, strOleDbConnectionString);

        ins.Connection.Open();

        ins.ExecuteNonQuery().ToString();

        ins.Connection.Close();

Solution

  • looks like a simple error in your query..

    if User is a string (don't know about the rest) it should be simple quoted

    "INSERT INTO jiahe ([Tag ID], User, Age, [Phone Number]) VALUES (123, 'Esther', 19, 92786618)"
    

    Also, the oledbcommand receive a connection object, not a connection string. try with

    OleDbCommand ins = new OleDbCommand(insertString, objConnection );