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.
Related
I am trying to insert bulk records in a sql server database table using dataset. But i am unable to do transaction handling. Please help me to apply transaction handling in below code.
I am using adapter.UpdateCommand.Transaction = trans; but this line give me an error of Object reference not set to an instance of an object.
Code:
string ConnectionString = "server=localhost\\sqlexpress;database=WindowsApp;Integrated Security=SSPI;";
SqlConnection conn = new SqlConnection(ConnectionString);
conn.Open();
SqlTransaction trans = conn.BeginTransaction(IsolationLevel.Serializable);
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Test ORDER BY Id", conn);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.UpdateCommand.Transaction = trans;
// Create a dataset object
DataSet ds = new DataSet("TestSet");
adapter.Fill(ds, "Test");
// Create a data table object and add a new row
DataTable TestTable = ds.Tables["Test"];
for (int i=1;i<=50;i++)
{
DataRow row = TestTable.NewRow();
row["Id"] = i;
TestTable .Rows.Add(row);
}
// Update data adapter
adapter.Update(ds, "Test");
trans.Commit();
conn.Close();
If the data-adapter doesn't make it easy to pass in a transaction, and doesn't handle it internally, then you might be able to force it by using TransactionScope instead - since this is ambient rather than explicit.
However! My main guidance here would be more simple: stop using data-sets and data-adapters. They were essentially hangover from pre-.NET patterns, and were handy when the data tooling for .NET was in an early state. It is no longer in that state. Virtually any other data access tool would be preferable.
I could not test your code, but I think you should also pass the connection of the trans object to your adapter like in the following example:
...
adapter.UpdateCommand.Connection = trans.Connection;
adapter.UpdateCommand.Transaction = trans;
...
Good luck!
Source: CodeProject
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
}
I am attempting to update a simple ms access database. I get an Exception on certain tables that, after searching, I found Microsoft Support - Syntax Error. I believe it means that one of the column names uses a reserved word. This seems to be the case, since all the tables update except the ones with "GUID" as one of the column names, a reserved word. This page also states that I should be using a OleDbAdapter and DataSet, which should solve the problem. Unfortunately I cannot change the name of the column. That is beyond my control, so I have to work with what is given me.
I haven't had to do work with databases much, and everything I know I've learned from examples from the internet (probably bad ones at that). So what is the proper way to update a database using OleDbAdapter and dataSet?
I don't think I should be using DataTable or OleDbCommandBuilder, and I believe the solution has something to do with parameters. But my googleing skills are weak.
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; " +
Data Souce=" + source);
conn.Open();
OleDbAdapter adapter = new OleDbDataAdapter("SELECT * From " + table, conn);
OleDbCommandBuiler cmdBuiler = new OleDbCommandBuilder(adapter);
DataSet = new DatSet();
adapter.InsertCommand = cmdBuilder.GetInertCommand(true); // Is this necessary?
adapter.Fill( dataSet, table);
DataTable dataTable = dataSet.Tables[table]; // Do I need a DataTable?
DataRow row = dataTable.
row [ attribute ] = field; // Do this for all attributes/fields. I think this is wrong.
dataTable.rows.Add(row);
adapter.Update(dataTable); //<--"Syntax error in INSERT INTO statement." Exception
The problem may be that the column names (especially those whose name are reserved words) should be surrounded by square brackets. The OleDbCommandBuilder, when it creates its own InsertCommand, doesn't surround the names with brackets, so a solution is to manually define the OleDbDataAdapter's InsertCommand:
adapter.InsertCommand = new OleDbCommand(String.Format("INSERT INTO {0} ([GUID], [fieldName]) Values (#guid,#fieldName);", table), conn);
Defining parameters for each column and then manually adding the parameter's values;
adapter.InsertCommand.Parameters.Add(new OleDbParameter("#guid",row["GUID"]));
So summing up, for the tables which have a column named "GUID", you should try something like the following:
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Souce=" + source);
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * From " + table, conn);
OleDbCommandBuilder cmdBuilder = new OleDbCommandBuilder(adapter);
adapter.InsertCommand = new OleDbCommand(String.Format("INSERT INTO {0} ([GUID], [fieldName]) Values (#guid,#fieldName);", table), conn);
DataTable dataTable = new DataTable(table);
adapter.Fill( dataTable);
DataRow row = dataTable.NewRow();
row [ fieldName ] = fieldValue;
// eg: row [ "GUID" ] = System.Guid.NewGuid().ToString(); // Do this for all attributes/fields.
dataTable.Rows.Add(row);
adapter.InsertCommand.Parameters.Add(new OleDbParameter("#fieldName",row[fieldName]));
// eg: adapter.InsertCommand.Parameters.Add(new OleDbParameter("#guid",row["GUID"]));
adapter.Update(dataTable);
As to problem #1. Try doing a full qualification of the column name i.e. table.columnName (that fixes the problem in MySQL so maybe it does in Access) also, try putting [ ] around the column name.
Select * is usually a poor option to specifying the column names and using aliases. For example use Select Column1 as 'Column1', Column2 as 'Column2' ....
this makes working with your dataset and datatable much easier as you can access the column by its alias instead of by column indexes.
I find that the DataAdapter is much more useful for filling datasets than for actually modifying a database. I recommend something like:
string updateQuery = "Update ..... Where ...."; //do your magic here
OldDbcommand command = new OleDbCommand(updateQuery);
command.Connection = conn;
conn.Open();
con.ExecuteNonQuery();
conn.Close();
You could fill your dataset with the adapter and then do as I just did to execute your update commands on the DB.
A good place to start would be using DataSetDesigner and Typed DataSets to start
try this walk through : http://msdn.microsoft.com/en-us/library/ms171893(v=vs.80).aspx
A good longterm approach is to use Sql Server Express instead, then you'll have a choice of using : Entity Framework, Linq To Sql or Still keep using the DataSetDesigner and Typed DataSets.
NOTE: This is the simple version of my previous question that SHOULD have been written.
I have two tables in the same SQL Server database, TestTable and TestTable2. Neither has a primary key. Each have two columns,
TestInt (int)
TestString (varchar(50))
There is data in TestTable2, while TestTable is empty. I want to copy the contents of one into the other, via C#. (I know this can be done in SQL, but humor me here.)
Here is the code I've written to do the job, using a SqlDataAdapter object...
// Data in TestTable2, nothing in TestTable.
private static void Main(string[] args)
{
SqlConnection conn = /* CONNECTION CREATION CODE */
string sqlQuery = "SELECT * FROM TestTable2";
DataTable payload = /* SIMPLE QUERY CODE USING sqlQuery */
// CODE CHECKPOINT #1
sqlQuery = "SELECT * FROM TestTable";
SqlCommand sCmd = new SqlCommand(sqlQuery, conn);
SqlDataAdapter sDA = new SqlDataAdapter(sCmd);
DataSet dataSet = new DataSet();
conn.Open();
sDA.Fill(dataSet);
conn.Close();
for (int i = 0; i < payload.Rows.Count; i++)
{
dataSet.Tables[0].ImportRow(payload.Rows[i]);
}
// CODE CHECKPOINT #2
SqlCommandBuilder cb = new SqlCommandBuilder(sDA);
conn.Open();
sDA.Update(dataSet);
conn.Close();
}
The problem is that this code is not working. If I were to check the contents of DataTable 'payload' at Checkpoint #1, I see 4 rows, while there are 0 rows in dataSet.Tables[0]. If I then check the contents of 'dataSet' at Checkpoint #2, I see 4 rows in dataSet.Tables[0]! However, at the end of the program, none of the rows from TestTable2 have made it into TestTable.
In other words, C# is moving the data between the DataTables, but it is having no affect on the tables themselves.
I've found that adding newly created rows
DataRow row = DataSet.DataTable.NewRow(...);
...
dataSet.Tables[i].Rows.Add(row);
into the destination DataSet works with SqlDataAdapter.Update, but that's not appropriate in this case, as you cannot use DataTable.Rows.Add on a row held by a separate DataTable. Hence, my problem, as this has rendered me incapable of transfering data from one table to another, especially in cases where large numbers of column are involved, rendering explicit SQL commands very clunky.
Is there something I'm missing in this code that I'm not seeing? If so, what is it?
Thanks.
Try DataSet.AcceptChanges() before updating data to the DB. Also, check, what the DataSet.GetChanges() method returns. It should not be an empty DataSet.
Finally, I have found the solution here:
importrow --> update fails
The ultimate answer is a translation of the link provided by platon. However, I'm including the explicit code here for easier future reference.
Basically, ImportRow doesn't always set the dirty bit for the added rows. As a result, SqlDataAdapter.Update won't necessarily move the changes to SQL since it doesn't recognize the new rows as changed data. To insure that the dirty bit is set, you need to call DataTable.Rows.Add, but as mentioned this cannot be called using the row of another table as a parameter.
What to do? Don't use the row as a parameter to Add(). Instead, use the object[] ItemArray...
for(int i = 0 ; i < srcTable.Rows.Count ; i++)
{
destTable.Rows.Add(srcTable.Rows[i].ItemArray);
}
...
SqlCommandBuilder sCB = new SqlCommandBuilder(adapter);
adapter.Update(dataSet);
I need to open a connection to SQL database and read a subset of a table and either update a record if exists or insert if not found. Having truoble updating
SqlConnection conn = new SqlConnection(ConnectionStrings.PgenIntranet.SqlClientConnectionString);
SqlDataAdapter indicators = new SqlDataAdapter();
string sql = "SELECT * FROM BusinessApplications.tbl_WPI_Site_Indicators where Year = '" + year +
"' and Month = '" + month + "' and PlantId = " + site.ID;
indicators.SelectCommand = new SqlCommand(sql, conn);
SqlCommandBuilder cb = new SqlCommandBuilder(indicators);
indicators.UpdateCommand = cb.GetUpdateCommand();
DataSet ds = new DataSet();
indicators.Fill(ds, "indtable");
DataTable indtable = ds.Tables["indtable"];
// this logic not working
if (indtable.Rows.Count == 0) { indtable.NewRow(); }
DataRow dr = indtable.NewRow();
/// not sure how to make this work
indtable[1]["PlantId"] = site.ID;
dr["PlantId"] = site.ID;
It's been a while since I've used DataSets/DataTables/DataRows, but I think you're close. If I remember correctly, you'll need to create a new row object like you do here:
DataRow dr = indtable.NewRow();
Then populate that row with your data, also similar to how you were doing it:
dr["PlantId"] = site.ID;
Then finally add that row to the rows collection in the DataTable. (You'll want to double-check if your DataTable instance is actually the DataTable in the Tables collection on the DataSet, I don't recall the specifics. It may be safer to reference the Tables collection directly rather than put it in its own object.)
Note that this does not add the row back to the database. It just adds it to the DataTable instance. You'll need to update back to the database accordingly. And this setup that you have here is a bit... messy... so I have no quick answer for that. Since you're just using plain old ADO then I guess you'll need to create an update command and populate it and run it against the connection accordingly.
In doing so, please take care to fix SQL injection vulnerabilities like the one you have there :)
Don't forget to add your new row to the table, then call update...
indtable.Rows.Add(dr);
ds.Update();