Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why two rows getting added to my SQLite database table?

When I add data to my SQLite database table using the below code, it adds 2 identical rows to the table for some reason instead of one.

    using(SQLiteConnection conn= new SQLiteConnection(@"Data Source="+Path.GetFullPath("./TestDB.db")+";"))
    {
        conn.Open();

        SQLiteCommand command = new SQLiteCommand("INSERT INTO Test(FirstName, LastName, Age) VALUES('Chris','Pine',42)", conn);
        command.ExecuteNonQuery();
        
        SQLiteDataAdapter adap = new SQLiteDataAdapter(command);
        
        DataTable dt = new DataTable("Test");
        adap.Fill(dt);
        
        dataGrid1.ItemsSource=dt.DefaultView;
        adap.Update(dt);
        
        conn.Close();

    }
    
    MessageBox.Show("Complete!");
    refreshdata();

Why is this happening ?

Also, the code for refreshdata

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public void refreshdata()
{
    
    using(SQLiteConnection conn= new SQLiteConnection(@"Data Source="+Path.GetFullPath("./TestDB.db")+";"))
        
    {
        conn.Open();

        SQLiteCommand command = new SQLiteCommand("Select * from Test", conn);
        command.ExecuteNonQuery();
        
        SQLiteDataAdapter adap = new SQLiteDataAdapter(command);
        
        DataTable dt = new DataTable("Test");
        adap.Fill(dt);
        
        dataGrid1.ItemsSource=dt.DefaultView;
        adap.Update(dt);
        
        conn.Close();

    }

>Solution :

You are calling ExecuteNonQuery and you are giving the adapter an INSERT command in place of its SelectCommand.

SQLiteDataAdapter adap = new SQLiteDataAdapter(command);

That line of code uses a the constructor that sets the adapter’s SelectCommand. When you Fill() the datatable, it calls the SelectCommand, but in your case it is an INSERT statement.

Really, you should not be doing anything with an Adapter there, you should just ExecuteNonQuery and then call refreshdata.

And you can remove the call to Update() in refreshdata(), it is not necessary.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading