在日常编写程序的时候我们总是会遇到一次性插入多条数据,但是这多条数据中有的数据有可能和我们数据库中字段的类型不一样或者字段类型的长短不一样导致无法插入数据库。在这种情况下我们的需求是这次插入的数据都不能被插入到数据库。方法使在C#中使用事务。
0)创建数据表
/****** Object: Table [dbo].[ClassDemo] Script Date: 01/29/2014 10:07:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ClassDemo](
[id] [int] IDENTITY(1,1) NOT NULL,
[name] [nvarchar](10) NULL,
[address] [nvarchar](10) NULL,
PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
1)Web.config中添加连接数据库的语句
<add key="ConnectionString" value="server=.\sqlexpress;database=ClassDemo;uid=sa;pwd=1"/>
2)在表示层Default.aspx.cs中添加多条需要插入数据库的数据(由于name字段的长度是10,但是这里插入的“张三3张三3张三312”的长度是11所以无法插入数据库,不能提交应该回滚)。
public void Add()
{
List<Maticsoft.Model.ClassDemo> modellist = new List<Maticsoft.Model.ClassDemo>();
modellist.Add(new Maticsoft.Model.ClassDemo("张三1", "浙江1"));
modellist.Add(new Maticsoft.Model.ClassDemo("张三2", "浙江2"));
modellist.Add(new Maticsoft.Model.ClassDemo("张三3张三3张三312", "浙江3"));
bll.Add(modellist);
}
3)在数据访问层和DbHelperSQL.cs中添加将数据插入数据库的代码如下
/// <summary>
/// 通过事务添加多条数据
/// </summary>
/// <param name="modellist"></param>
public void Add(List<ClassDemo> modellist)
{
Hashtable SQLStringList = new Hashtable();
for (int i = 0; i < modellist.Count; i++)
{
SqlParameter[] parameters = {
new SqlParameter(string.Format("@name{0}",i), SqlDbType.NVarChar,50),
new SqlParameter(string.Format("@address{0}",i), SqlDbType.NVarChar,50)};
parameters[0].Value = modellist[i].Name;
parameters[1].Value = modellist[i].Address;
SQLStringList.Add(string.Format("insert into ClassDemo (name,address) values (@name{0},@address{0})", i), parameters);
}
ExecuteSqlTran(SQLStringList);
}
public static string connectionString = ConfigurationManager.AppSettings["ConnectionString"].ToString();
/// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param>
public static void ExecuteSqlTran(Hashtable SQLStringList)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlTransaction trans = conn.BeginTransaction())
{
SqlCommand cmd = new SqlCommand();
try
{
//循环
foreach (DictionaryEntry myDE in SQLStringList)
{
string cmdText = myDE.Key.ToString();
SqlParameter[] cmdParms = (SqlParameter[])myDE.Value;
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
trans.Commit();
}
catch (Exception ex)
{
trans.Rollback();
}
}
}
}
private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = CommandType.Text;//cmdType;
if (cmdParms != null)
{
foreach (SqlParameter parameter in cmdParms)
{
if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
(parameter.Value == null))
{
parameter.Value = DBNull.Value;
}
cmd.Parameters.Add(parameter);
}
}
}