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
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();
}
CodePudding user response:
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.