Search code examples
c#oledb

Insert query is run successfully, but the data is not inserted into the database (C#)


public partial class Form1 : Form
{
    OleDbConnection connection = new OleDbConnection(check.Properties.Settings.Default.KitchenConnectionString);

    public Form1()
    {
        InitializeComponent();
    }

    private void btn_add_Click(object sender, EventArgs e)
    {
        OleDbDataAdapter items = new OleDbDataAdapter();
        connection.Open();

        OleDbCommand command = new OleDbCommand("insert into Sets(SetId, SetName,  SetPassword) values('"+txt_id.Text+ "','" + txt_setname.Text + "','" + txt_password.Text + "');", connection);
        command.CommandType = CommandType.Text;

        command.ExecuteReader();

        connection.Close();

        MessageBox.Show("Inserted!");
    }
}

Solution

  • Given that it's Ole, I'm guessing this is Access - a file based database. Your insert is running successfully but you don't find the data in the db when you look

    You need to appreciate that typically withba probe t that uses an access db you will have several copies of the db but the most relevant ones are probably like:

    C:\myprojects\windowsapp1\your.accdb 
    C:\myprojects\windowsapp1\bin\debug\your.accdb 
    

    The first one is the db you see in the solution explorer. The second one is placed next to your debug exe every time you run a build, or possibly every time you click play in VS. The second one is probably the db your program is inserting into

    You're either looking in the wrong db for your data, or every time you run your program the build process erases the changes db by copying the empty one (first one) over the top of it.

    Run your app, insert your data, don't quit your app, Search your entire project folder for all instances of your db file. Look in all of them. You'll probably find your data

    • Right click the db file in solution explorer, choose properties, and change the Copy action to Copy If Newer

    Now the build process will only erase your db in the debug folder if you make a change to the source db, eg add a table to it etc