c#向数据表中插入多条记录
- 格式:doc
- 大小:41.50 KB
- 文档页数:7
在用c#进行数据库编程时,经常遇到主从表的处理,需要同时更新多个表多条记录,用Update,它是遍历了整个数据集进行修改,但是好像并没有进行事务处理.请问,如何一次更新多个表多条记录进行事务处理.另外,如何联合用存储过程来处理又该怎样. 问题点数:50、回复次数:6Top1 楼henryfan1()回复于2003-02-27 11:06:17 得分0在SqlDataAdapter在构造设置SelectCommand的事务,对应更新就会产生事务。
关于事务处理不多说,查看MSDN.Top2 楼yhcnux()回复于2003-02-27 11:06:34 得分10一种方法,在数据库中建存储过程,而这个存储过程中用到事务,另一种方法,用自带的手动事务处理,我给你一段我的源码:public void AddBargain(ArrayList arr){//执行事务using (SqlConnection con = new SqlConnection(conStr) ){con.Open();using (SqlTransaction trans = con.BeginTransaction()){//传参SqlParameter[] myParms1 = {SqlHelper.MakeInParam("@bargaindate",SqlDbType.VarChar,50,arr[0]),SqlHelper.MakeInParam("@salesman",SqlDbType.VarChar,80,arr[1]),SqlHelper.MakeInParam("@principal",SqlDbType.VarChar,80,arr[2]),SqlHelper.MakeInParam("@customerid",SqlDbType.Int,4,arr[3])};SqlParameter[] myParms2 = {SqlHelper.MakeInParam("@bargainfilename",SqlDbType.VarChar,50,arr[4]),SqlHelper.MakeInParam("@bargainfile",SqlDbType.Image,16,arr[5])};try{//执行存储过程,把信息插入Bargain表中SqlHelper.ExecuteNonQuery(trans, CommandType.StoredProcedure, "AddBargain1", myParms1 );//执行存储过程,把信息插入BargainFileSqlHelper.ExecuteNonQuery(trans, CommandType.StoredProcedure, "AddBargain2", myParms2 );mit();}catch (Exception ex){// throw exceptiontrans.Rollback();throw ex;}finally{con.Close();}}}}格式比较乱,你凑合着看吧。
SqlHelper类是我用来访问数据库的包含静态方法的类。
AddBargain1和AddBragain2分别是添加合同的信息到两个不现的表的存储过程,要保持同步,一个表添加失败,另一个表也不应该添加。
Top3 楼visualpony(pony)回复于2003-02-27 11:12:28 得分20只要准备了 .NET 框架类参与自动事务,此类的实例就可以参与自动事务。
类实例或对象访问的每个资源都在事务中登记。
例如,如果一个对象使用 发送数据库中某帐户上的钱,此数据库的资源管理器将确定该对象是否在事务中执行。
如果对象是在事务中执行,则资源管理器自动在事务中登记此数据库。
使用下列过程准备参与自动事务的类:将TransactionAttribute 应用于此类。
从ServicedComponent 类派生此类。
用强名称为程序集签名。
若要使用特性为程序集签名,请使用Sn.exe 实用工具创建一个密钥对。
sn -k TestApp.snk添加AssemblyKeyFileAttribute 或AssemblyKeyNameAttribute 程序集特性(它们指定包含密钥对的文件的名称),以使用强名称为程序集签名。
[Visual Basic]<assembly: AssemblyKeyFileAttribute("TestApp.snk")>[C#][assembly: AssemblyKeyFileAttribute("TestApp.snk")]有关详细信息,请参阅使用强名称为程序集签名。
向COM+ 目录注册包含此类的程序集。
如果类的客户端调用实例是由公共语言运行库管理的,则注册将自动执行。
但是,如果预期非托管调用方可能创建和调用类的实例,请使用 .NET 服务安装工具(Regsvcs.exe) 手动执行注册。
下列示例显示如何将TransactionAttribute 应用到从ServicedComponent 类派生的类。
[Visual Basic]<Transaction(TransactionOption.Required)> Public Class BarInherits ServicedComponent'. . .End Class[C#][Transaction(TransactionOption.Required)]public class Bar(): ServicedComponent{//. . .}应用事务特性时,可以交替使用Transaction、transaction、TransactionAttribute 和transactionattribute。
例如,可以使用Transaction 或transactionattribute 产生相同的结果。
下表列出并描述每个构造函数变体。
特性值说明Disabled 消除自动事务对对象的控制。
应用此特性值的对象可以直接将分布式事务处理协调器(DTC) 用于事务性支持。
[Transaction(TransactionOption.Disabled)]NotSupported 指示对象不在事务范围内运行。
处理请求后,不管是否有活动事务,均在没有事务的情况下创建其对象上下文。
[Transaction(TransactionOption.NotSupported)]Supported 指示如果有事务,则对象在现有事务的上下文中运行。
如果没有事务,则对象在没有事务的情况下运行。
[Transaction(TransactionOption.Supported)]Required(默认值)指示对象需要事务。
如果有事务,则对象在现有事务范围中运行。
如果没有事务,则对象启动一个事务。
[Transaction(TransactionOption.Required)]RequiresNew 指示对象需要事务且为每个请求启动新事务。
[Transaction(TransactionOption.RequiresNew)]下列代码示例说明自动事务的若干元素。
此例中,事务性类和调用此类的客户端都由运行库管理。
[Visual Basic]' -----------------------------------------------------------------' TestApp.vb' Generate a Strong name:' sn -k TestApp.snk' Compile the code:' vbc /target:exe /r:System.EnterpriseServices.dll TestApp.vb' Run TestApp:' start TestApp.exe' -----------------------------------------------------------------Option ExplicitOption StrictImports SystemImports pilerServicesImports System.EnterpriseServicesImports System.Reflection'Registration details.'COM+ application name as it appears in the COM+ catalog.<assembly: ApplicationName("TestApp")>'Strong name for assembly.<assembly: AssemblyKeyFileAttribute("TestApp.snk")><Transaction(TransactionOption.Required)> Public Class AccountInherits ServicedComponent'Provides SetComplete behavior in the absence of exceptions.<AutoComplete()> Public Sub Debit(amount As Integer)' Do some database work. Any exception thrown here aborts the' transaction; otherwise, transaction commits.End SubEnd ClassPublic Class clientPublic Shared Sub Main()Dim accountX As New Account()accountX.Debit(100)Environment.Exit(0)End SubEnd Class// -----------------------------------------------------------------// TestApp.cs// Generate a Strong name:// sn -k TestApp.snk// Compile the code:// csc /target:exe /r:System.EnterpriseServices.dll TestApp.cs// Run TestApp:// start TestApp.exe// -----------------------------------------------------------------using System;using pilerServices;using System.EnterpriseServices;using System.Reflection;//Registration details.//COM+ application name as it appears in the COM+ catalog. [assembly: ApplicationName("TestApp")]//Strong name for assembly.[assembly: AssemblyKeyFileAttribute("TestApp.snk")][Transaction(TransactionOption.Required)]public class Account : ServicedComponent{//Provides SetComplete behavior in the absence of exceptions.[AutoComplete]public void Debit(int amount){// Do some database work. Any exception thrown here aborts the // transaction; otherwise, transaction commits.}}public class client{public static int Main(){Account accountX = new Account();accountX.Debit(100);return 0;}}Top4 楼yhcnux()回复于2003-02-27 11:13:03 得分20另:这里是执行参数为事务的数据库操作的静态方法(SqlHelper类中的)public static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandT ype, string commandText, params SqlParameter[] commandParameters){//create a command and prepare it for executionSqlCommand cmd = new SqlCommand();PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters);//finally, execute the command.int retval = cmd.ExecuteNonQuery();// detach the SqlParameters from the command object, so they can be use d again.cmd.Parameters.Clear();return retval;}其中调用到这个方法:private static void PrepareCommand(SqlCommand command, SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlPar ameter[] commandParameters){//if the provided connection is not open, we will open itif (connection.State != ConnectionState.Open){connection.Open();}//associate the connection with the commandcommand.Connection = connection;//set the command text (stored procedure name or SQL statement) mandText = commandText;//if we were provided a transaction, assign it.if (transaction != null){command.Transaction = transaction;}//set the command typemandType = commandType;//attach the command parameters if they are providedif (commandParameters != null){AttachParameters(command, commandParameters);}return;}其实,对数据库的操作,我使用的是微软的SqlHelper类,一是比较严密,二是能省不少代码。