• datatable与SqlDataReader


     
    datatable的认识:

    以前只是用过用datatable来保存从数据库中获得的数据却不知道在得到数据

    后也可以自己添加有关数据。例如下面的例子:
     SqlDataAdapter da = new SqlDataAdapter("select * from users", "data

    source=.;Initial catalog=coment_db;Integrated Security=true");
                DataTable dt = new DataTable();
                da.Fill(dt);
                dataGridView1.DataSource = dt;
                dt.Columns.Add("性别", typeof(int));

                dt.Columns.Add("男女", typeof(string), "IIF([id]

    =1,'女',IIF([id]=5,'男','人妖'))");

                dt.Rows.Add(1);
                dt.Rows.Add(0);

                DataRow dr = dt.NewRow();
                dr[0] = 1;
                dr[1] = "桂素伟";
                dr[2] = "222222";

                dt.Rows.Add(dr);
    注意dt.Columns.Add()中可以有三个参数。而第三个参数可以使任何的表达

    式:例如:IIF([id]=1,'女',IIF([id]=5,'男','人妖'))或者sum 、avg等函

    数。在DataRow dr = dt.NewRow();时注意不要去new出DataRow它的对象。
    再看下面的例子:
                //dt.Columns.Add("单价", typeof(double));
                //dt.Columns.Add("数量", typeof(int));
                //dt.Columns.Add("金额", typeof(double), "单价*数量");
                //dt.Rows.Add(23.5, 5);
                //dt.Rows.Add(35, 10);
                //dt.Rows.Add(40, 2);
                //DataRow dr = dt.NewRow();
                //dr[0] = 1.6;
                //dr[1] = 67;
                //dt.Rows.Add(dr);
    这个例子告诉我们dt.Columns.Add()中第三个参数可以运算而且是两个列名

    的相乘。和一些如上面的例子使用时的类似的应用。
    下面谈谈SqlDataReader的一些特性:
    using (SqlConnection con = new SqlConnection("Initial

    catalog=coment_db;Integrated Security=true"))
                {
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = con;
                    cmd.CommandText = "SELECT * FROM getsexcount

    ('true')";
                    cmd.Parameters.Clear();
                    cmd.Parameters.Add("@tssex", SqlDbType.Bit).Value =

    radioButton1.Checked;
                    try
                    {
                        con.Open();
                        SqlDataReader dr = cmd.ExecuteReader();
                       // DataTable dt = new DataTable();
                        //dt.Load(dr);
                       // dataGridView3.DataSource = dt;
      //另一种方法
       while (sdr.Read())
                    {

                        listBox1.Items.Add(sdr.GetValue(0).ToString() +

    "-" + sdr.GetValue(1).ToString() + "-" + sdr.GetValue(2).ToString

    ());
                    }
                    sdr.Close();
                    }
                    catch (Exception exc)
                    {
                        MessageBox.Show(exc.Message);
                    }
                    finally
                    {
                        con.Close();
                    }
    上面的例子是SqlDataReader的两种使用方法,注意sdr.Read()是一次读取一

    行,读一行返回一行。
    那么我们就来说说SqlDataReader与DataTable的区别:DataTable为内存表,

    当把数据库中的数据读取到DataTable中时,我们在界面上做操作时是对内存

    表的操作并没有改变数据库表的内容。SqlDataReader为长连接,当连接关闭

    时将无法再进行读取数据,它是只读且只进的数据。
    下面我们谈谈存储过程的使用和事务的使用:
    存储过程:带输出参数的存数过程。
     using (SqlConnection con = new SqlConnection("Initial

    catalog=coment_db;Integrated Security=true"))
                {
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = con;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "TSMessageCount";//存储过程名称
                    cmd.Parameters.Clear();
                    cmd.Parameters.Add("@begindt",

    SqlDbType.DateTime).Value = dateTimePicker1.Value;
                    cmd.Parameters.Add("@enddt",

    SqlDbType.DateTime).Value = dateTimePicker2.Value;

                    SqlParameter SP = new SqlParameter();
                    SP.ParameterName = "@Count";
                    SP.SqlDbType = SqlDbType.Int;
                    SP.Direction = ParameterDirection.Output;
                    cmd.Parameters.Add(SP);

                    try
                    {
                        con.Open();
                        cmd.ExecuteNonQuery();
                        MessageBox.Show(SP.Value.ToString());//注意我们

    需要得到输出参数的值

                        
                    }
                    catch(Exception exc)
                    {
                      MessageBox.Show(exc.Message);
                     }
                    finally
                    {
                        con.Close();
                    }
                }

    下面是事务的具体应用的例子:
     SqlConnection conn = new SqlConnection("Initial

    catalog=coment_db;Integrated Security=true");
                SqlTransaction sta = null;
                try
                {
                    conn.Open();
                    sta = conn.BeginTransaction();
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = conn;
                    cmd.Transaction = sta;
                    cmd.CommandText = "insert into tsmessage values

    ('aaaa',1,GetDate(),1)";
                    cmd.ExecuteNonQuery();

                    SqlCommand cmd1 = new SqlCommand();
                    cmd1.Connection = conn;
                    cmd1.Transaction = sta;
                    cmd1.CommandText = "delete tspersons  where 1=2";
                    cmd1.ExecuteNonQuery();
                    sta.Commit();
                }
                catch
                {
                    sta.Rollback();
                }
                finally
                {
                    conn.Close();
                }
    只有当上面的两条语句都执行成功时,才会提交到数据库表中否则会回滚事务

    。两条都不会执行。
    下面看看用自定义函数是想的功能:
     //调用sql自定议函数返回值为单值的函数
            private void button9_Click(object sender, EventArgs e)
            {
                using (SqlConnection con = new SqlConnection

    ("server=.;database=coment_db;uid=sa;pwd=sa;"))
                {
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = con;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "MyGsw";
                    cmd.Parameters.Clear();
                    cmd.Parameters.Add("@sex", SqlDbType.Bit).Value =

    radioButton1.Checked;

                    SqlParameter sp = new SqlParameter();
                    sp.Direction = ParameterDirection.ReturnValue;
                    sp.SqlDbType = SqlDbType.Int;
                    cmd.Parameters.Add(sp);              

                    DataTable dt = new DataTable();
                    try
                    {
                        con.Open();
                        cmd.ExecuteReader ();
                        MessageBox.Show(sp.Value .ToString ());         

             
                    }
                    catch (Exception exc)
                    {
                        MessageBox.Show(exc.Message);
                    }
                    finally
                    {
                        con.Close();
                    }
                }
            }
            //调用sql中自定义函数返回值为表的函数 
            private void button10_Click(object sender, EventArgs e)
            {

                using (SqlConnection con = new SqlConnection

    ("server=.;database=coment_db;uid=sa;pwd=sa;"))
                {
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = con;            
                    cmd.CommandText = "select * from MyTable(@sex)";
                    cmd.Parameters.Clear();
                    cmd.Parameters.Add("@sex", SqlDbType.Bit).Value =

    radioButton1.Checked;
                    try
                    {                   
                        con.Open();          
                        SqlDataReader dr = cmd.ExecuteReader();
                        DataTable dt = new DataTable();
                        dt.Load(dr);
                        dataGridView1.DataSource = dt;
                    }
                    catch (Exception exc)
                    {
                        MessageBox.Show(exc.Message);
                    }
                    finally
                    {
                        con.Close();
                    }
                }
            }

    本文出自 “zhangjingjing” 博客,请务必保留此出处http://zhjjzhjj.blog.51cto.com/1802676/385731

  • 相关阅读:
    组合模式
    过滤器模式
    桥接模式
    适配器模式
    原型模式
    建造者模式
    抽象工厂
    工厂方法
    静态工厂
    单例模式
  • 原文地址:https://www.cnblogs.com/wzq806341010/p/2868433.html
Copyright © 2020-2023  润新知