Remove Row through DataAdapter - c#

I've initialized a dataAdapter :
string sql = "SELECT * From localitati";
da1 = new System.Data.SqlClient.SqlDataAdapter(sql, con);
da1.Fill(ds1, "localitati");
And this works just fine. The problem is when i try to delete a record and update the database.
I remove a record from the dataset as such :
ds1.Tables["localitati"].Rows.Remove(dRow);
And this works just fine as well(verified).
The problem is when i update the DataAdapter, the DataBase doesn't get modified :
con.Open()
da1.Update(ds1, "localitati");
con.Close();
What could be the problem ?

What fixed it for me was to call the Delete method on the DataRow instead of the Remove method on the DataTable.
ds.Tables["localitati"].Rows.Find(primaryKeyValue).Delete();
or just simply
dr.Delete();

You need to make sure you've set the da1.DeleteCommand - this is the command that will be fired for each row in the DataTable that has been deleted. See this MSDN reference for example.

try below code
assuming that Database is not throwing any exception.
con.Open()
da1.Update(ds1.Tables["localitati"].GetChanges());
con.Close();

In the code that you have posted only the SelectCommand is set for the DataAdapter.
You could use the following code to generate the Insert, Update and Delete commands for da1.
string sql = "SELECT * From localitati";
da1 = new SqlDataAdapter(sql, con);
SqlCommandBuilder builder = new SqlCommandBuilder(da1);
builder.QuotePrefix = "[";
builder.QuoteSuffix = "]";
da1.Fill(ds1, "localitati");
The CommandBuilder however should be used only for relatively simple scenarios (details). For he rest is recommended to write your own commands that rely on custom command texts/stored procedures.
If it still doesn't work, you could start a SQL Server Profiler on the server to trace what command gets to the database when you execute the Update method.

DataRow dr = datatable.Rows.Find(key);
int Index = datatable.Rows.IndexOf(dr);
BindingContext[DataTable].RemoveAt(Index);
BindingContext[DataTable].EndCurrentEdit();
dataAdapter.Update(DataTable);
DataTable.AcceptChanges();

Related

DataSet call insert, update and delete stored procedures

Through designer I have created a typed data set and included stored procedures for insert / update / delete. The problem is now, how to call those stored procedures? How to actually change data in database this way? And how to receive answer from db (number of rows changed)?
try this for get data from database.
DataSet ds = new DataSet("dstblName");
using(SqlConnection conn = new SqlConnection("ConnectionString"))
{
SqlCommand sqlComm = new SqlCommand("spselect", conn);
sqlComm.Parameters.AddWithValue("#parameter1", parameter1value);
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlComm;
da.Fill(ds);
}
Similarly you need to call "spdelte" etc.
I found out that far easiest way is through designer - create table adapter and simply set it to call stored procedure. No extra typing needed, arguments are also added to procedure call.

Update using MySqlDataAdapter doesn't work

I am trying to use MySqlDatAdapter to update a MySql table. But, the table never updates!!! I did this before but with SQL server. Is there anything else that is specific to MySql that I am missing in my code?
DataTable myTable = new DataTable("testtable");
MySqlConnection mySqlCon = new MySqlConnection(ConfigurationManager.ConnectionStrings["DBConStr"].ConnectionString);
MySqlCommand mySqlCmd = new MySqlCommand("SELECT * FROM testtable WHERE Name = 'Tom'");
mySqlCmd.Connection = mySqlCon;
MySqlDataAdapter adapter = new MySqlDataAdapter(mySqlCmd);
MySqlCommandBuilder myCB = new MySqlCommandBuilder(adapter);
adapter.UpdateCommand = myCB.GetUpdateCommand();
mySqlCon.Open();
adapter.Fill(myTable);
myTable.Rows[0]["Name"] = "Was Tom";
myTable.AcceptChanges();
adapter.Update(myTable);
mySqlCon.Close();
Thanks
Remove myTable.AcceptChanges() before the update. Othwerwise that will set all rows RowState to Unchanged, hence the DataAdapter will not know that something was changed.
adapter.Update(myTable) will call AcceptChanges itself after the update is finished.
So...
myTable.Rows[0]["Name"] = "Was Tom";
//myTable.AcceptChanges();
adapter.Update(myTable);
My some one need to look into the following solution; In other scenario people may need different solution. Even Don't do any manipulation with Datatable when you Debug at Run-time like this,
myTable.GetChanges(); // Return Any of Chnages Made without applying myTable.Accepchanges()
myTable.GetChanges(DataRowState.Added); // Return added rows without applying myTable.Accepchanges()
myTable.GetChanges(DataRowState.Deleted);
myTable.GetChanges(DataRowState.Detached);
myTable.GetChanges(DataRowState.Modified);
myTable.GetChanges(DataRowState.Unchanged);
You may get Data According to the above commands. So better try to debug before you pass the datatable to update or insert or delete command.
If myTable.GetChanges() return null then you can SetAdded() or SetModified() back to your DataTable;
foreach(DataRow row in myTable.Rows)
{
row.SetAdded(); // For Insert Command
row.SetModified(); // For Update Command
}

Problem with ADO.NET UPDATE code

Could somebody take a quick peek at my ado.net code? I am trying to update the row from a dataset, but it just isn't working. I am missing some elemental piece of the code, and it is just eluding me. I have verified that the DataRow actually has the correct data in it, so the row itself is accurate.
Many thanks in advance.
try
{
//basic ado.net objects
SqlDataAdapter dbAdapter = null;
DataSet returnDS2 = new DataSet();
//a new sql connection
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = "Server=myserver.mydomain.com;"
+ "Database=mydatabase;"
+ "User ID=myuserid;"
+ "Password=mypassword;"
+ "Trusted_Connection=True;";
//the sqlQuery
string sqlQuery = "select * from AVLUpdateMessages WHERE ID = 21";
//another ado.net object for the command
SqlCommand cmd = new SqlCommand();
cmd.Connection = myConn;
cmd.CommandText = sqlQuery;
//open the connection, execute the SQL statement and then close the connection.
myConn.Open();
//instantiate and fill the sqldataadapter
dbAdapter = new SqlDataAdapter(cmd);
dbAdapter.Fill(returnDS2, #"AVLUpdateMessages");
//loop through all of the rows; I have verified that the rows are correct and returns the correct data from the db
for (int i = 0; i <= returnDS2.Tables[0].Rows.Count - 1; i++)
{
DataRow row = returnDS2.Tables[0].Rows[i];
row.BeginEdit();
row["UpdatedText"] = #"This is a test...";
row.EndEdit();
}
//let's accept the changes
dbAdapter.Update(returnDS2, "AVLUpdateMessages");
returnDS2.AcceptChanges();
myConn.Close();
}
I think you need an update query in your data adapter. I know, this sucks... Alternatively you can use CommandBuilder class to automatically generate queries for CRUD operations.
example at: http://www.programmersheaven.com/2/FAQ-ADONET-CommandBuilder-Prepare-Dataset
You might be able to use SqlCommandBuilder to help out. After the Fill call, add the following statement. That will associate a command builder with the data adapter and (if there is a primary key available) it should generate the update statement for you. Note that there is some expense behind the command builder. It may not be much relative to everything else, but it does involve looking at schema information (to get primary key information, field names, field types, etc.) for the table and generating INSERT, DELETE, and UPDATE statements involving all fields in the table.
SqlCommandBuilder cb = new SqlCommandBuilder(dbAdapter);
Wait, why not something like
update AVLUpdateMessages set UpdatedText = 'This is a test...' where id = 21
If you're picking through all the rows of a table to update one at a time, you're probably doing it wrong. SQL is your friend.

How to force SQL query return updated data in .NET?

My C# program connects to a user request SQL database, gets the first open request, process it and mark the request as closed. Then I get the next open request.
The problem is that I always get the same request back from SQL Query although it is marked as 'closed'. I suspect I get a cached result instead of updated data. But I don't know how to clear that cache.
I tried to dispose the SQLDataAdpater and create new one every time. I also tried to add a random number as parameter to the SQL Select stored procedure. None of them worked.
Can anyone please help me on this issue? Thanks.
The Sql query is:
Select Top(1) RequestID, RequestType, RequestXML from Request
where RequestStatus='OP'
SQL Update command:
begin tran
Update Request Set RequestStatus=#RequestStatus where RequestID=#RequestID;
if (#RequestXML is not null)
Update Request Set RequestXML=#RequestXML where RequestID=#RequestID;
commit tran
C# Code:
SqlDataAdapter da = new SqlDataAdapter("SrvGetOpenRequest", cn);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
SqlCommand cmd = new SqlCommand("SrvUpdateRequest", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("RequestID", SqlDbType.Int);
cmd.Parameters.Add("RequestStatus", SqlDbType.Char);
cmd.Parameters.Add("RequestXML", SqlDbType.Xml);
DataTable dt = new DataTable();
cn.Open();
da.Fill(dt);
cn.Close();
while (dt.Rows.Count > 0)
{
// Process returned datatable here.
..............
cmd.Parameters["RequestStatus"].Value = "CL";
cn.Open();
cmd.ExecuteNonQuery();
// fetch the next request to process
da.Fill(dt);
cn.Close();
}
I did checked the database and the record was marked as closed.
Try calling dt.Clear() before filling it again.
Fill method adds rows to existing DataTable
Post some code, please. It's possible that you're not actually persisting the changes you make locally back to your actual database, which is why you keep getting the original unchanged data back from your query. It may also be possible that you're making the changes inside a transaction, but then not committing the transaction.
Does DataAdapter.Fill clear the DataTable first? I wonder if you're appending new rows to the end of the DataTable each time?

Help with DataAdapter - DB doesn't update?

I have a data adapter. When I check the function at runtime I see the changes, but nothing happens in the database. How do I debug this? What went wrong?
OleDbDataAdapter adapter = new OleDbDataAdapter();
string queryString = "SELECT * FROM tasks";
OleDbConnection connection = new OleDbConnection(cn.ConnectionString);
adapter.SelectCommand = new OleDbCommand(queryString, connection);
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
connection.Open();
adapter.Fill(ds.Tables["Tasks"]);
adapter.Update(ds);
return ds;
Nothing is happening in the database because you're running a SELECT query. What are you expecting to happen?
Well unless you snipped a lot of code, you are not changing anything in the dataset per se.
What are you trying to achieve?
Here, you are selecting some data, filling the dataset with it, then putting back the unchanged dataset in the DB.
You should first change something in the dataset itself before calling adapter.Update(ds)
Cheers,
Florian
You are selecting data via the SelectCommand. If you want to update data, you need to run the UpdateCommand.
I assume you didn't post the full source code, as it looks as though you're not modifying the dataset. However, I just tweaked your code a bit (see my comments).
Hopefully this will help...
string queryString = "SELECT * FROM tasks";
OleDbConnection connection = new OleDbConnection(cn.ConnectionString);
connection.Open(); // open connection first
SqlCommand cmd = new SqlCommand(queryString, connection);
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd); // use the cmd above when instantiating the adapter
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
adapter.Fill(ds.Tables["Tasks"]);
// Modify your dataset here.
// Don't call AcceptChanges() as this will prevent the update from working.
adapter.Update(ds);
connection.Close(); // Close connection before ending the function
return ds;
This should allow OleDbCommandBuilder to do its thing by automatically scripting the database updates.
As far as I can see you've not actually changed any of the contents of the tasks table. When you call adapter.Fill you are populated the empty dataset with the records from the database. You are then calling adapter.Update without changing any records within the dataset. The update command only performs changes when the dataset > datatable > datarows are edited and marked as dirty.
you are only specifying the select command. you also need to specify the insert command... i.e:
DataAdapter.InsertCommand = new OleDbCommand....

Categories