transaction handling in dataset based insert/update in c#

Posted by user3703611 on Stack Overflow See other posts from Stack Overflow or by user3703611
Published on 2014-06-10T09:13:43Z Indexed on 2014/06/10 9:24 UTC
Read the original article Hit count: 189

Filed under:
|
|

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();

© Stack Overflow or respective owner

Related posts about c#

Related posts about sql-server