More efficient delete of Sql table from DataTable by identifier - c#

I have to insert-delete a Sql table using a C# DataTable. My two strategies are
delete one row at a time, or
throw the DataTable into a stored procedure and do delete where exists.
Neither strategy is preferred to me as #1 is inefficient and #2 requires some setting up (user schemas, stored procedure, etc.).
Is there another (better) way?
//place buy_detail_id into distinct datatable
DataView view = new DataView(table);
DataTable distinctIds = view.ToTable(true, "buy_detail_id");
//strategey 1: delete one row at a time by Id
foreach (DataRow row in distinctIds.Rows)
{
//delete one row at a time
DeleteRow(row[0]);
}
//strategy 2: throw DataTable into a stored proc as parameter
//then delete where buy_detail_id exists in distinctIds

Related

Can't select DataRow from DataTable

I'm trying to prevent inserting duplicated data into MS Access table like below,
MS Access table(Record) with Columns: Situation, Check_Item, and starts with no data in the table.
DataTable from DataSet is filled with the query "SELECT * FROM Record WHERE Situation = 'A'".
Then I try to do this process,
DataRow = DataTable.Select("Check_Item = '"+InputTextBox.Text"'");
If (DataRow.Length == 0)
{
Use OleDbCommand to insert InputTextBox.Text string to Check_Item of Record table.
}
Result:
First time key in(e.g. 123456), because there is no data in the table, so 123456 is inserted into Record table.
But at the second time key in 123456, then it still be inserted into Record table.
What happened in this process??
Assuming your DataTable variable has name table, and that you created it and linked it correctly to your MS Access database then:
DataRow[] rows = table.Select("Check_Item = '"+InputTextBox.Text"'"); //Selects all rows where the condition is met.
If (rows.Length == 0)
{
//No row met the condition so create a new one and add it to the table.
DataRow newRow = table.NewRow(); //Creates a new row with the same schema (columns) as the table.
newRow["Check_Item"] = InputTextBox.Text; //Assigns the value.
table.Rows.Add(newRow); //Adds the new row to the row collection of the table.
table.AcceptChanges(); //Commits and persist the changes done to the table.
}
Be sure to check this and also the official docs for DataTable.

database not affected by dataset after renewing a table

I have a dataset that contains a table. This table has just a column (without primary key). My table is shown in a datagridview. Now, I want to edit data of table. So, I store data of table in a DataTable and then, I clear all data of table in dataset and fill it by DataTable, like this:
DataView dv = ((BindingSource)tblMyTableDataGridView.DataSource).SyncRoot as DataView;
DataTable dt = dv.ToTable();
IDataReader dr = dt.CreateDataReader();
myDataSet.tblMyTable.Clear();
myDataSet.tblMyTable.Load(dr);
By breaking point, that specified that tblMyTable has changed truely.
But it not affected on database. My code is:
tableAdapterManager.tblMyTableTableAdapter.Update(myDataSet.tblMyTable);
tableAdapterManager.UpdateAll(myDataSet);
What is wrong?!?!?
Thanks.

Why doesn't my SQLite database table update? (datatable update)

I have a c# application with an SQLite database. It has a table called "Results_to_Risks" which I am trying to update. I first remove some rows in my local datatable, after which I use my update table function to update the table in the database.
foreach(var row in temp)
{
allResToRisks.Rows.Remove(row);
}
_databaseController.UpdateTable(allResToRisks, "Results_to_Risks");
My database controller update table method:
// Updates an entire database table.
public void UpdateTable(DataTable datatable, string table, string condition = "")
{
using (SQLiteConnection dbConnection = new SQLiteConnection(conString))
{
using (var sqliteAdapter = new SQLiteDataAdapter("SELECT * FROM '" + #table + "'" + #condition, dbConnection))
{
dbConnection.Open();
using(var builder = new SQLiteCommandBuilder(sqliteAdapter))
{
sqliteAdapter.Update(datatable);
}
}
}
}
In this particular case, I remove just one row. The datatable ends up empty (Rows.Count == 0), because this was the only row in that datatable. So nothing goes wrong there. However my table in the database still has the one row inside it.
What am I doing wrong?
I saw this on the MDSN website:
It is important to understand the difference between deleting a row in a DataTable and removing the row. When you call the Remove or RemoveAt method, the row is removed immediately. Any corresponding rows in the back end data source will not be affected if you then pass the DataTable or DataSet to a DataAdapter and call Update. When you use the Delete method, the row remains in the DataTable and is marked for deletion. If you then pass the DataTable or DataSet to a DataAdapter and call Update, the corresponding row in the back end data source is deleted.
So i tried to use Delete() instead of Remove(). However, this made no difference.

Appending DataRow to DataTable filled from DataAdapter, clears all records

I have a DataGridView that has a DataTable bound to it, populated from PostgreSQL database with Npgsql .NET data provider library.
Populating records works, but when I want to append just a single records to already existing DataTable, previous records vanish:
NpgsqlDataAdapter npDataAdapterSingle = new NpgsqlDataAdapter("SELECT * from \"Weight\" ORDER BY id DESC LIMIT 1", this.npConnection);
DataTable tmpTable = new DataTable("tmpTable");
npDataAdapterSingle.Fill(tmpTable);
DSWeight.WeightRow row = this.dSWeight.Weight.NewWeightRow();
row.ItemArray = tmpTable.Rows[0].ItemArray;
this.dSWeight.Weight.Rows.InsertAt(row, 0); //Prepend, but i also tried this.dsWeight.Weight.Rows.Add(row);
If I select all records, without LIMIT'ing, then it works as expected. But I thought - why would i need to query the database all over again if I already have those records? That's why I want to LIMIT.
Maybe there is another solution, because I manually add new records to database and query them to add them to datatable, not the way it is supposed to be: add new records to datatable and them to database. I do it this way because I want the database to manage the id and timestamp fields and have datagridview to have these fields populated.
What am I missing?
Am not sure about the data type of DSWeight.WeightRow and the scope of 'this' object since I get to see only a portion of the code and not the full method. This should probably work for you. please have a try.
NpgsqlDataAdapter npDataAdapterSingle = new NpgsqlDataAdapter("SELECT * from \"Weight\" ORDER BY id DESC LIMIT 1", this.npConnection);
DataTable tmpTable = new DataTable("tmpTable");
npDataAdapterSingle.Fill(tmpTable);
row = tmpTable.NewRow();
foreach (DataColumn col in tmpTable.Columns)
row[col.ColumnName] = tmpTable.Rows[0][col.ColumnName];
tmpTable.Rows.Add(row, 0);

DataTable to SQL CE 4 Server

I have a DataTable in C# and would like to send it to my SQL CE 4 server. One thing that makes it a bit more complicated is that when it encounters an duplicate, it should either ignore it and move on to the next row in the DataTable. I've looked around but a lot of information I find doesn't seem to work with the CE version of SQL Server. What's an efficient way of doing this?
Filter your DataTable to exclude the duplicate rows before uploading, using the DataTable.Select Method
e.g.
DataTable table = DataSet1.Tables["Orders"];
// Presuming the DataTable has a column named Date.
string expression;
expression = "Date > #1/1/00#"; // you will need logic to remove your duplicates
DataRow[] foundRows;
// Use the Select method to find all rows excluding duplicates
foundRows = table.Select(expression);
// .NET 3.5 onwards
DataTable filteredDataTable = foundRows.copyToDataTable();
Try this Logic.
var dt = new DataTable(); //Supposed that this is your DataTable
foreach(DataRow row in dt.Rows)
{
var find = MyFindMethod("Id"); 1. select statement that find if the id is on database
if(find.Rows > 0)
{
//Id exist do nothing
}
else
{
//Id not exist then 2. Do Insert to sql ce id I not exist
MyInsertMethod("Id");
}
}
Regards

Categories