Update database from dataset

J

Jimmy

Hi all,

I am new to .NET, Any idea that I can't get the below to work?

It gave me this error:
<An unhandled exception of type 'System.Data.SqlClient.SqlException'
occurred in system.data.dll
Additional information: System error.>

Any help would be greatly appreciated.


Assumption: myConnectionString is correctly defined.
----------------------------------------------------
SqlConnection myConn = new SqlConnection(myConnectionString);
SqlDataAdapter myDataAdapter = new SqlDataAdapter();
myDataAdapter.SelectCommand = new SqlCommand("SELECT * FROM customer",
myConn);

SqlCommandBuilder custCB = new SqlCommandBuilder(myDataAdapter);

myDataAdapter.UpdateCommand = custCB.GetUpdateCommand();

myConn.Open();

DataSet custDS = new DataSet();
myDataAdapter.Fill(custDS,myTableName);

//code to modify data in dataset here
//**** NOTE: it go works fine if I take out this line ***//
custDS.Tables[0].Rows[0]["Description"] = "new description";

//**** Error generated here ***
myDataAdapter.Update(custDS, myTableName);

myConn.Close();
----------------------------------------------------------
 
F

fbhcah

Hi Jimmy,

FYI, you needn't explicitly set the data adapter's update command.

Does the table have at least a primary key or unique key column?

HTH,
fbhcah
 
J

Jimmy Tieu

The table definitely has a primary key. I have checked every possibility
of the error but stil couldn't get it working properly.

Love to more help from you.
 
J

Jon Skeet [C# MVP]

Ravichandran J.V. said:
AcceptChanges is missing?

Usually, client code shouldn't call AcceptChanges itself - the data
adapter does it at the end of the Update call.
 
R

Ron Allen

Jimmy,
If one of the field names returned by the select is a reserved word you
will get an error. Try setting the QuotePrefix and QuoteSuffix properties
of the CommandBuilder with either backticks (`) or "[" and "]" and see if
that works.
If you don't modify the table the update won't do anything so it will
work.
If this still doen't work put the Update in a try block and catch the
SqlException to get its' message for more detail on the error.
Ron Allen
 
J

Jimmy Tieu

Thanks Ron,

It is as what you said, when I use "[" and "]" for prefix and postfix
then it works fine. Thanks alot for your help.

Now, I have another question. If we select a table that has no Primary
key defined, do we have to create our own SqlCommand, can't
CommandBuilder handle it. If it's the case then there is not much use
with CommandBuilder then.

Again, thank you all of you have participated in my post.

Regards,
Jimmy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top