第18课-数据库开发及ado.net 连接数据库.增.删.改向表中插入数据并且返回自动编号.SQLDataReade读取数据

18-数据库开发及ado.net

连接数据库...改向表中插入数据并且返回自动编号.SQLDataReade读取数据

ADO.NET

为什么要学习?

我们要搭建一个平台(Web/Winform)让用户方便的操作数据库中的数据。

什么是ADO.NET

是一组库类,System.Data.

Ado.net组成

Connection:用来连接数据库

Command:用来执行SQL语句

DataReader:只读、只进的结果集,一条一条读取数据(SteamReader、XmlReader)

DataAdapter:一个封装了上面3个对象的对象。

数据集(DataSet),临时数据库。

断开式数据操作

Ado.net 中其它常见类

ConnectionStringBuilder  --自动生成连接字符串

Parameter  --带参数的SQL语句

Transaction  --在ADO.NET中使用事务

与DataSet相关的类

DataView ---视图类,DataTable 中的数据以不同的视角查看

DataRowView --- DataView的行

DataTable ---DataSet中的数据表

DataRow --- DataTable中的行

DataColumn --- DataTable中的列

DataRealation --- DataTable与DataTable的关系

Contraint ---DataTable中建立的约束

#region 通过ado.net连接数据库

            //1.编写连接字符串

            string constr = "Data Source=127.0.0.1\\BLEACHMSSQL;Initial Catalog=itcast2013;user=sa;Password=root";

            //string constr = "Data Source=127.0.0.1\\BLEACHMSSQL;Persist Security Info=True;User ID=sa";

            //使用windows身份验证方式

            //string constr="Data Source=127.0.0.1\BLEACHMSSQL;Initial Catalog=itcast2013;Integrated Security=true";

            //2.创建连接对象

            SqlConnection con = new SqlConnection(constr);

            //3.打开连接

            con.Open ();

            Console.WriteLine ("使用连接对象");

            //4.关闭连接

            con.Close ();

            //5.释放资源

            con.Dispose ();

            Console .WriteLine ("连接关闭,并释放资源");

            Console .WriteLine ("OK");

            Console .ReadKey ();

            #endregion

 

            //另外一种连接方式

            string constr1 = "Data Source=127.0.0.1\\BLEACHMSSQL;Initial Catalog=itcast2013;Integrated Security=true";

            using (SqlConnection con1 = new SqlConnection(constr1))

            {

                //con1.Open();

            }

            Console.ReadKey();

            //第一个对象Connection

            //1.数据库不可以重复打开

            string constr2 = "Data Source=127.0.0.1\\BLEACHMSSQL;Initial Catalog=itcast2013;user=sa;Password=root";

            using (SqlConnection  con2=new SqlConnection (constr2))

            {

                con2.Open();

                Console.WriteLine("第一次打开数据库连接");

                /////数据库不可以重复打开

                // con2.Open();

                // Console.WriteLine("第二次打开数据库连接");

                //判断数据库是否已打开

                if (con2.State == System.Data.ConnectionState.Closed)//ConnectionState枚举

                {

                    con2.Open();//如果当前数据库已经关闭,则再次打开。

                }

                con.Close();//关闭连接,相当于设置障碍

                con.Dispose();//相当于把路拆了,这块地可以盖楼了。

                Console.ReadKey();

            }

       /// <summary>

        /// 添加操作

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void button1_Click(object sender, EventArgs e)

        {

            //向TblPerson表中插入一条记录

            //1.连接数据库

            //连接字符串

            string constr = "Data Source=127.0.0.1\\BLEACHMSSQL;Initial Catalog=itcast2013;user=sa;Password=root";

            //创建连接对象

            using (SqlConnection con=new SqlConnection (constr) )

            {

                //打开数据库连接

                //如果con对象是其它地方传递过来的一个对象,则在打开前最好判断con.State

                con.Open();

                //向表中插入一条数据

                //先构建一个sql语句

                string sql = string.Format("insert into TblPerson(uname,uage,uheight) values('{0}','{1}','{2}')", "黄林", 18, 175);

                //执行sql语句需要一个“命令对象”

                //创建一个命令对象

                using (SqlCommand cmd=new SqlCommand (sql,con))

                {

                    #region SqlCommand对象常用的三个方法

                    //执行sql语句

                    //当执行 insert,delete,update语句时,一般使用该方法

                    //cmd.ExecuteNonQuery()

                    //当执行返回单个值的SQL语句时使用该方法

                    //cmd.ExecuteScalar()

                    //当执行sql语句返回多行多列时候,一般使用该方法。查询。

                    //cmd.ExecuteReader ()

                    #endregion

 

                    //这里要执行insert语句所以用ExecuteNonQuery()方法

                    //通过调用该方法就会将insert语句交给数据库引擎来执行

                    //这个方法的返回值是一个Int类型,表示当前Sql语句执行后所影响的行数

                    int r = cmd.ExecuteNonQuery();

                    con.Close();

                    Console.WriteLine("成功插入{0}行", r);

                }

            }

        }

        /// <summary>

        /// //删除操作

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void button2_Click(object sender, EventArgs e)

        {

            //删除操作

            string constr = "Data Source=127.0.0.1\\BLEACHMSSQL;Initial Catalog=itcast2013;user=sa;Password=root";

            string sql = string.Format("delete from TblPerson where autoId={0}",19);

            using (SqlConnection con = new SqlConnection(constr))

            {

                using (SqlCommand cmd=new SqlCommand (sql,con))

                {

                    //尽可能晚的开启

                   con.Open();

                   int r= cmd.ExecuteNonQuery();

                    //使用完毕尽可能早的关闭连接

                   con.Close();

                   Console.WriteLine("成功删除{0}行", r);

                }

            }

            MessageBox.Show("Ok");

        }

        /// <summary>

        /// 更新操作

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void button3_Click(object sender, EventArgs e)

        {

            //更新操作

            string constr = "Data Source=127.0.0.1\\BLEACHMSSQL;Initial Catalog=itcast2013;user=sa;Password=root";

            string sql = string.Format("update  TblPerson set uname='{0}'  where autoId={1}", "许正龙",40);

            using (SqlConnection con = new SqlConnection(constr))

            {

                using (SqlCommand cmd = new SqlCommand(sql, con))

                {

                    //尽可能晚的开启

                    con.Open();

                    int r = cmd.ExecuteNonQuery();

                    //使用完毕尽可能早的关闭连接

                    con.Close();

                    Console.WriteLine("成功更新{0}行", r);

                }

            }

            MessageBox.Show("Ok");

        }

异常处理

可以使用try…catch…finally 来捕获异常

/// <summary>

        /// 查询及异常处理方法

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void button4_Click(object sender, EventArgs e)

        {

            //显示表中的记录的条数

            string constr = "Data Source=127.0.0.1\\BLEACHMSSQL1;Initial Catalog=itcast2013;user=sa;Password=root";

            string sql = "select count(*) from TblClass";

            int r = 0;

            try

            {

                using (SqlConnection con = new SqlConnection(constr))

                {

                    using (SqlCommand cmd = new SqlCommand(sql, con))

                    {

                        try

                        {

                            con.Open();

                            r = Convert.ToInt32(cmd.ExecuteScalar());

                            con.Close();

                            //Console.WriteLine("成功更新{0}行", r);

                        }

                        catch (Exception ex1)

                        {

                            Console.WriteLine("发生了异常:" + ex1.Message);

                        }

                        finally

                        {

                            con.Close();

                            con.Dispose();

                        }

                    }

                }

            }

            catch (Exception ex)

            {

                Console.WriteLine("发生了异常:"+ex.Message );

            }

          

            MessageBox.Show("表中有"+ r +"条记录");

        }

ConnectionStringBuilder类演示

        private void button1_Click(object sender, EventArgs e)

        {

            SqlConnectionStringBuilder connStrbuilder = new SqlConnectionStringBuilder();

            connStrbuilder.DataSource = "127.0.0.1\\BLEACHMSSQL";

            connStrbuilder.InitialCatalog = "itcast2013";

            connStrbuilder.IntegratedSecurity = true;

            connStrbuilder.Pooling = true;

            MessageBox.Show(connStrbuilder.ConnectionString);

        }

 

        private void Form1_Load(object sender, EventArgs e)

        {

            SqlConnectionStringBuilder connStrbuilder = new SqlConnectionStringBuilder();

            propertyGrid1.SelectedObject = connStrbuilder;

        }

        /// <summary>

        /// 向表中插入数据,返回自动编号

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void button5_Click(object sender, EventArgs e)

        {

            //连接字符串

            string constr = "Data Source=127.0.0.1\\BLEACHMSSQL;Initial Catalog=itcast2013;user=sa;Password=root";

            string sql = string .Format ("insert into TblClass output inserted.tClassId values('{0}','{1}')",textBox1 .Text .Trim (),textBox2 .Text .Trim());

            //其中,inserted 是一个触发器

            int tclassId = -1;

            using (SqlConnection  con=new SqlConnection (constr))

            {

                using (SqlCommand cmd=new SqlCommand (sql,con))

                {

                    cmd.StatementCompleted += new StatementCompletedEventHandler(cmd_Statementcompleted);

                    con.Open();

                    tclassId =Convert.ToInt32 ( cmd.ExecuteScalar());

                    con.Close();

                }

            }

            MessageBox.Show("成功插入,主键ID为:"+ tclassId +"");

       

        }

        private void cmd_Statementcompleted(object sender, StatementCompletedEventArgs e)

        {

            //输出每条Sql语句执行所影响的行数。

            throw new NotImplementedException();

        }

查询表中的所有记录

            #region 将TblPerson表中的数据输出到控制台

            string constr = "Data Source=127.0.0.1\\BLEACHMSSQL;Initial Catalog=itcast2013;user=sa;Password=root";

            string sql = "select * from TblPerson";

            using (SqlConnection con=new SqlConnection (constr))

            {

                using (SqlCommand cmd=new SqlCommand (sql,con))

                {

                    con.Open();

                    using (SqlDataReader reader = cmd.ExecuteReader())

                    {

                        //判断当前的reader是否读取到了数据

                        if (reader .HasRows)

                        {

                            ///通过列名来获取列的值,将索引写在循环外面,提高效率[建议使用该方式]

                            int autoIdIndex=reader .GetOrdinal ("autoId");

                            int unameIndex = reader.GetOrdinal("uname");

                            int uageIndex = reader.GetOrdinal("uage");

                            int uheightIndex = reader.GetOrdinal("uheight");

                            //循环读取每一条数据

                            while (reader .Read ())

                            {

                                #region 通过SqlDataReader的索引器和GetValue()方法获取列值

                                //通过reader获取行中列的方法一。

                                //通过reader的所引起可以使用列索引,也可以使用列名。reader["列名"];(性能比较高)

                                //强烈建议使用列索引,如果必须要使用列名,也要使用列索引。

                                //读取当前行中的每一列的数据

                                object obj1 = reader[0];

                                object obj2 = reader[1];

                                object obj3 = reader[2];

                                object obj4 = reader[3];

                                Console.WriteLine("{0}\t{1}\t{2}\t{3}\t", obj1, obj2, obj3, obj4);

                                //通过reader获取行中列的方法二。

                                //reader.GetValue()不支持列名,只支持列索引

                                object obj5 = reader.GetValue(0);

                                object obj6 = reader.GetValue(1);

                                object obj7 = reader.GetValue(2);

                                object obj8 = reader.GetValue(3);

                                //this.GetOrdinal(name);根据列名获取列的索引。

                                #endregion

                                #region 通过reader获取列值的时候,使用强类型

                                //autoId, uname, uage, uheight

                                //当使用强类型的时候,如果数据库中的值为null,则报错。

                                //避免方式:判断是否为null即可。

                                int autoId = reader.GetInt32(0);

                                string name = reader.GetString(1);

                                //int?表示可空值类型,

                                int? uage = reader.IsDBNull(2) ?null :(int?) reader.GetInt32(2);

                                int? height = reader.IsDBNull(3) ? null : (int?)reader.GetInt32(3);

                                Console.WriteLine("{0}\t{1}\t{2}\t{3}\t", autoId, name, uage, height);

                                #endregion

                                #region 通过列名来获取列的值[建议使用该方式]

                                Console.WriteLine("{0}\t{1}\t{2}\t{3}\t",

                                    reader.GetInt32(autoIdIndex),

                                    reader.GetString(unameIndex),

                                    reader.GetInt32(uageIndex),

                                    reader.GetInt32(uheightIndex));

                                #endregion

                            }

                        }

                    }

                 

                }

            }

            Console.WriteLine("OK");

            Console.ReadKey();

            #endregion

        }

把表中的数据绑定到控件上

            #region 将TblPerson表中的数据输出到控制台

            string constr = "Data Source=127.0.0.1\\BLEACHMSSQL;Initial Catalog=itcast2013;user=sa;Password=root";

            string sql = "select * from TblPerson";

            List <Person> list=new List<Person>();

            using (SqlConnection con = new SqlConnection(constr))

            {

                using (SqlCommand cmd = new SqlCommand(sql, con))

                {

                    con.Open();

                    using (SqlDataReader reader = cmd.ExecuteReader())

                    {

                        //判断当前的reader是否读取到了数据

                        if (reader.HasRows)

                        {

                            ///通过列名来获取列的值,将索引写在循环外面,提高效率[建议使用该方式]

                            int autoIdIndex = reader.GetOrdinal("autoId");

                            int unameIndex = reader.GetOrdinal("uname");

                            int uageIndex = reader.GetOrdinal("uage");

                            int uheightIndex = reader.GetOrdinal("uheight");

                            //循环读取每一条数据

                            while (reader.Read())

                            {

                                

                                #region 通过列名来获取列的值[建议使用该方式]

                                //Console.WriteLine("{0}\t{1}\t{2}\t{3}\t",

                                //    reader.GetInt32(autoIdIndex),

                                //    reader.GetString(unameIndex),

                                //    reader.GetInt32(uageIndex),

                                //    reader.GetInt32(uheightIndex));

                                Person model = new Person();

                                model.AutoId = reader.GetInt32(autoIdIndex);

                                model.UName  = reader.GetString(unameIndex);

                                model.UAge = reader.IsDBNull(uageIndex) ? null : (int?)reader.GetInt32(uageIndex);

                                model.UHeight = reader.IsDBNull(uheightIndex) ? null : (int?)reader.GetInt32(uheightIndex);

                                list.Add (model);

                                #endregion

                            }

                        }

                    }

 

                }

            }

            dataGridView1.DataSource = list;

            #endregion

    /// <summary>

    /// 创建Person类,autoId, uname, uage, uheight

    /// </summary>

    public  class Person

    {

        public int AutoId

        {

            get;

            set;

        }

        public string UName

        {

            get;

            set;

        }

        public int? UAge

        {

            get;

            set;

        }

        public int? UHeight

        {

            get;

            set;

        }

    }

posted @ 2016-08-13 14:15  阳光少年1712  阅读(489)  评论(0编辑  收藏  举报