zoukankan      html  css  js  c++  java
  • SqlClient类库下的常用操作(一)

      EntityFrameWork4.1已经面世多日了,其好处在EF讨论模块已经很多了,但本人还是认为SQL文还是不能忘,

    C#操作sql server的类库用法也不能忘,通过运用SqlClient类库下的类访问数据库更能理解访问原理。

    --摘自MSDN Start--

      SqlConnection类:表示sql server数据源的一个连接。或者表示sql server数据源的一个唯一的会话。

      SqlCommand类:表示要对 SQL Server 数据库执行的一个 Transact-SQL 语句或存储过程。

      SqlDataAdapter类: 表示用于填充DataSet和更新 SQL Server 数据库的一组数据命令和一个数据库连接。

      SqlCommandBuilder类:自动生成单表命令,用于将对DataSet所做的更改与关联的 SQL Server 数据库的更改相协调。

      SqlParamater类:表示SqlCommand的参数,也可以是它到DataSet列的映射。

      SqlTransaction类:表示要在 SQL Server 数据库中处理的 Transact-SQL 事务。

    --摘自MSDN End--

    从例子看以上各个类之间的协作。

    1.查询

    假定connectionString已经定义好。

    View Code
    1 using (SqlConnection conn =new SqlConnection(connectionString))
    2 {
    3 //连接打开
    4   conn.Open();
    5 //创建命令
    6   SqlCommand command =new SqlCommand("Select * from Orders", conn);
    7 //执行命令返回SqlDataReader类型结果
    8   SqlDataReader reader = command.ExecuteReader();
    9 try
    10 {
    11 while (reader.Read())
    12 {
    13 Console.Write(string.Format("{0},{1}", reader[0], reader[1]));
    14 }
    15 }
    16 finally
    17 {
    18 //最后总是关闭reader对象
    19   reader.Close();
    20 if (conn.State != ConnectionState.Closed) conn.Close();
    21 }
    22 }

    2.单笔更新

    2.1:使用SqlCommandBuilder类来实现

    View Code
    1 publicvoid rpt_Pro_List_Bind(string ordresId,string ordersName)
    2 {
    3 using (SqlConnection conn =new SqlConnection(connectionString))
    4 {
    5 //连接打开
    6   conn.Open();
    7
    8 //使用SelectCommand和SqlConnection初始化SqlDataAdapter对象
    9 //若没有使用SelectCommand和SqlConnection初始化SqlDataAdapter对象
    10 //就必须设置adapter.SelectCommand = new SqlCommand(QueryString, conn)
    11 //SelectCommand 必须至少返回一个主键列或唯一的列。
    12 //如果什么都没有返回,就会产生 InvalidOperation 异常,不生成命令。
    13 SqlDataAdapter adapter =new SqlDataAdapter("select * from Orders where OrdersId"+ordresId, conn);
    14 DataTable dt =new DataTable();
    15
    16 //将数据源填充到DataTable对象
    17 adapter.Fill(dt);
    18
    19 //重新赋值
    20 dt.Rows[0]["OrdersName"] = ordersName;
    21
    22 //生成用于表单更新的SQL命令,也可以这么写:
    23 //SqlCommandBuilder commandBuilder = new SqlCommandBuilder(adapter);
    24 //commandBuilder.GetUpdateCommand();
    25 new SqlCommandBuilder(adapter);
    26
    27 //执行更新
    28 adapter.Update(dt);
    29 }
    30 }

     2.2 不使用SqlCommandBuilder类实现

    View Code
    1 publicvoid rpt_Pro_List_Bind(string ordresId,string ordersName)
    2 {
    3 string commandText ="update Orders set OrdersName = @OrdersName where OrdersId = @OrdersId";
    4 using (SqlConnection conn =new SqlConnection(connectionString))
    5 {
    6 //创建命令
    7 SqlCommand command =new SqlCommand(commandText, conn);
    8 //传入参数
    9 command.Parameters.Add(new SqlParameter("@OrdersName",ordersName));
    10 command.Parameters.Add(new SqlParameter("@OrdersId", ordresId));
    11 try
    12 {
    13 //连接打开
    14 conn.Open();
    15 //执行命令
    16 int iCount = command.ExecuteNonQuery();
    17 }
    18 catch (Exception ex)
    19 {
    20 Console.WriteLine(ex.Message);
    21 }
    22 finally
    23 {
    24 if (conn.State != ConnectionState.Closed) conn.Close();
    25 }
    26 }
    27 }

    2.3 使用存储过程更新

    此处省略存储过程内容,存储过程为sp_UpdateOrderByOrdersId 参数为@OrdersId varchar(10),@OrdersName varchar(20)

    View Code
    1 publicvoid rpt_Pro_List_Bind(string ordresId,string ordersName)
    2 {
    3 using (SqlConnection conn =new SqlConnection(connectionString))
    4 {
    5 //创建命令
    6 SqlCommand command =new SqlCommand("sp_UpdateOrderByOrdersId",conn);
    7 command.CommandType = CommandType.StoredProcedure;
    8
    9 //给参数赋值
    10 command.Parameters.Add(new SqlParameter("@OrdersId",SqlDbType.VarChar,10));
    11 command.Parameters.Add(new SqlParameter("@OrdersName", SqlDbType.VarChar,20));
    12 command.Parameters[0].Value = ordresId;
    13 command.Parameters[1].Value = ordersName;
    14 try
    15 {
    16 //连接打开
    17 conn.Open();
    18 //执行命令
    19 int iCount = command.ExecuteNonQuery();
    20 }
    21 catch (Exception ex)
    22 {
    23 Console.WriteLine(ex.Message);
    24 }
    25 finally
    26 {
    27 if (conn.State != ConnectionState.Closed) conn.Close();
    28 }
    29 }
    30 }

    3.同时插入多笔数据(事务控制)

    View Code
    1 publicvoid rpt_Pro_List_Bind(string ordresId,string ordersName)
    2 {
    3 using (SqlConnection conn =new SqlConnection(connectionString))
    4 {
    5 //连接打开
    6 conn.Open();
    7 //创建命令
    8 SqlCommand command =new SqlCommand();
    9
    10 SqlTransaction transaction =null;
    11 //开始事务
    12 //此时隔离级别为默认级别,建议使用带iso参数设定隔离级别
    13 transaction = conn.BeginTransaction();
    14
    15 //事务与连接、命令相关联
    16 command.Connection = conn;
    17 command.Transaction = transaction;
    18
    19 try
    20 {
    21 command.CommandText ="insert into Ordres (OrdersId,OrdersName) values ('0001','aaa')";
    22 command.ExecuteNonQuery();
    23 command.CommandText ="insert into Ordres (OrdersId,OrdersName) values ('0002','bbb')";
    24 command.ExecuteNonQuery();
    25 //提交事务
    26 transaction.Commit();
    27 }
    28 catch(Exception ex)
    29 {
    30 Console.WriteLine("Message:{0}", ex.Message);
    31 try
    32 {
    33 //执行回滚
    34 transaction.Rollback();
    35 }
    36 catch(Exception ex)
    37 {
    38 Console.WriteLine("Message:{0}", ex.Message);
    39 }
    40 }
    41 }
    42 }
  • 相关阅读:
    MVC的各个部分都有那些技术来实现?如何实现?
    JRE、JDK、JVM 及 JIT 之间有什么不同
    什么是竞态条件?举例说明
    【Spring】No converter found for return value of type: class java.util.ArrayList
    【Spring】org.springframework.web.context.ContextLoaderListen 报错
    【Spring】The matching wildcard is strict……
    【MySQL】目录、文件权限问题
    线程和锁
    【Git】Found a swap file by the name ".git/.MERGE_MSG.swp"
    【Maven】Mac 使用 zsh 后 mvn 命令就无效
  • 原文地址:https://www.cnblogs.com/willpan/p/SQLClient.html
Copyright © 2011-2022 走看看