• SQL Server中的查询



          本博文简介一下SQL Server中经常使用的几类查询及相关使用的方法。

          一、ExecuteScalar方法获取单一值

          ExecuteScalar方法是SqlCommand类的方法之中的一个,运行查询,并返回查询所返回的结果集中的第一行第一列。

          

        class Program
        {
            static void Main(string[] args)
            {   
    
                string strCon = "Data Source=192.168.24.193;Initial Catalog=charge_sys;User ID=sa;Password=123456";
                using (SqlConnection con = new SqlConnection(strCon))//使用连接池,使用完后自己主动关闭连接
                {
                    using (SqlCommand cmd = con.CreateCommand())
                    {
                        string sql = "select count(*) from User_Info";//定义sql语句,查询整个表的行数
                        cmd.CommandText = sql;
                        con.Open();
                        int count = Int32.Parse(cmd.ExecuteScalar().ToString());                                                                                                                //返回整个结果集的首行首列,是一个Object类型
                        Console.WriteLine(count);
    
                        cmd.CommandText = "select * from User_Info";//定义sql语句
                        string s = cmd.ExecuteScalar().ToString();                                                                                                                            //返回整个User_Info表的第一行并赋给字符串s
                        Console.WriteLine(s);//将结果打印输出
                        Console.ReadLine();
                    }
                }
            }
          运行结果例如以下图:

          

          二、ExecuteNonQuery方法运行增删改操作

          ExecuteNonQuery方法也是SqlCommand的方法之中的一个,对连接运行T-SQL语句并返回受影响的行数。举例:

          

    static void Main(string[] args)
            {   
    
                string strCon = "Data Source=192.168.24.193;Initial Catalog=charge_sys;User ID=sa;Password=123456";
                using (SqlConnection con = new SqlConnection(strCon))//使用连接池,使用完后自己主动关闭连接
                {
                    using (SqlCommand cmd = con.CreateCommand())
                    {
    
                        ///数据操作语言,增删改查
                        string ins = "insert into User_Info (userID) values ('123')";                 
    
                        con.Open();//连接数据库
                        cmd.CommandText = ins;
                        int res = cmd.ExecuteNonQuery(); //运行SQL语句返回受影响的行数
                        if (res > 0)
                        {
                            Console.WriteLine("成功插入" + res + "条记录");
                        }
                        else
                        {
                            Console.WriteLine("插入失败");
                        }
                        Console.ReadLine();
                    }
                }
            }
          运行结果例如以下图:

          

          三、BeginExecuteReader()和EndExecuteReader()异步查询大结果集

          所谓异步查询大结果集,就是假设数据量很大,那么在開始运行查询和结束查询这一过程中可能会须要耗费一段时间,在这段时间我们也能够让我们的程序去干一些别的事,就有了上述两种方法。举例:

          

            static void Main(string[] args)
            {   
    
                string strCon = "Data Source=192.168.24.193;Initial Catalog=charge_sys;User ID=sa;Password=123456";
                using (SqlConnection con = new SqlConnection(strCon))//使用连接池,使用完后自己主动关闭连接
                {
                    using (SqlCommand cmd = con.CreateCommand())
                    {
                        
                        //异步查询大结果集
                        cmd.CommandText = "waitfor delay '00:00:05' ;select * from User_Info";  //延迟5秒连接数据库
                        con.Open();
                        IAsyncResult  iar=cmd.BeginExecuteReader();  
                        //BeignExecuteReader方法推断异步查询是否完毕
    
                        //此处能够写入其它数据库操作
    
                        SqlDataReader  sdr=  cmd.EndExecuteReader(iar); 
                        //EndExecuteReader方法结束连接,并把数据存储到数据集中
                        while (sdr.Read())
                        {
                            Console.WriteLine(sdr[0]+"    "+sdr[1]);
                        }               
                        Console.ReadLine();
                    }
                }
            }
          因为延迟了5秒中,所以输出结果在5秒以后才出现例如以下:

          

          四、运行批量查询操作

          一般我们在用SQL语句查询时仅仅是查询到一条记录,那么怎样在一个表中同一时候插入或者更新多条记录呢,这就用到了多天T-SQL语句。举例:

          

        class Program
        {
            static void Main(string[] args)
            {   
    
                string strCon = "Data Source=192.168.24.193;Initial Catalog=charge_sys;User ID=sa;Password=123456";
                using (SqlConnection con = new SqlConnection(strCon))//使用连接池,使用完后自己主动关闭连接
                {
                    using (SqlCommand cmd = con.CreateCommand())
                    {
                        
                        //运行批量操作查询,同一时候运行多条SQL语句
                        
                        string sql = "update User_Info set UserName  ='888' where userID ='2'"
                            + "update User_Info set UserName  ='999' where userID ='3'";
                        //将两条T-SQL语句连接
    
                        con.Open();//打开数据库
                        cmd.CommandText = sql;
                        int res = cmd.ExecuteNonQuery(); //运行SQL语句返回受影响的行数
                        if (res > 0)
                        {
                            Console.WriteLine("成功插入" + res + "条记录");
                        }
                        else
                        {
                            Console.WriteLine("插入失败");
                        }
                        Console.ReadLine();
                    }
                }
            }
          运行结果例如以下:

          

          五、參数化查询

          我们在刚開始学习在应用程序中编写SQL语句时,一般使用拼接字符串,单引號、双引號什么都有,编写起来非常不方便,并且easy被SQL注入破坏敏感数据,既不安全,由此我们引入了參数化查询,顾名思义,就是将要查询的内容用參数取代。看以下的样例:

          

    <span style="font-family:Times New Roman;">static void Main(string[] args)
            {
                string conStr = "Data Source=192.168.24.193;Initial Catalog=charge_sys;User ID=sa;Password=123456";
                using (SqlConnection con = new SqlConnection(conStr))
                {
                   
                    using (SqlCommand cmd = con.CreateCommand())
                    {
                        cmd.CommandText  = "select * from User_Info where userID=@userid";
                        //第一种方法
                        //SqlParameter param = new SqlParameter();
                        //param.ParameterName = "username";
                        //param.SqlDbType = SqlDbType.Char;
                        //param.Size = 10;
                        //param.Value = "admin";
                        //con.Open();
    
                        //另外一种方法,直接使用AddWithValue方法直接给參数赋值
    
                        cmd.Parameters.AddWithValue("@userid", '1');
                        con.Open();
                        SqlDataReader sdr = cmd.ExecuteReader();
                        while(sdr.Read())
                        {
                            Console.WriteLine(sdr[0]+"   "+sdr[1]);
                        }
                        Console.ReadLine();
                    }
                }
            }
    
    </span>

          六、MuHipleActiveResultSet方法运行多活动结果集

         一般一个Connection对象仅仅支持一个活动操作,假设我们须要加入另外一个或其它的或,在SQL连接语句后加上MuHipleActiveResultSet=True就可以。这里就不在演示了,希望本博文能给您带来一些帮助。



          

          

  • 相关阅读:
    wp8 入门到精通
    C# 从入门到精通
    wp8 json2csharp
    wp8 安装.Net3.5
    delphi资源文件制作及使用详解
    delphi弹出选择对话框选择目录SelectDirectory 函数
    delphi 判断WIN8 , WIN8.1 , WIN10 系统版本
    外壳扩展创建快捷方式和获取快捷方式的目标对象
    文本究竟是使用哪种字
    用Delphi创建服务程序
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/3984963.html
Copyright © 2020-2023  润新知