《C#4.0程序设计与项目实战》——ADO.NET技术

数据库的访问的方式有两种:一种是直接数据访问,另外一种是不连接数据访问。
直接数据访问是一种最容易的访问数据库的方式。使用直接数据访问可以创建SQL命令并执行这些命令。使用直接数据访问时,并不需要在内存中保存信息的副本。当数据库连接打开后可以再一段时间内维持与数据库的交互,然后数据库连接就会迅速断开。不连接的数据访问将会在内存中的DataSet对象中保存数据的副本,在数据库连接断开后仍然能够操作这些数据。
一个ASP.NET页面在被请求后将会被加载到客户端,而且一旦页面加载完毕连接就会关闭。因此直接数据访问模型非常适合ASP.NET 页面,这样就不需要在内存中长时间保持数据的副本,从而节省了宝贵的内存资源。
简单的数据查询步骤如下:
(1)创建Connection\Command\DataReader对象
 (2)  使用DataReader对象从数据库获取信息,并显示在Web表单的空间里
(3)关闭连接
(4)发送页面到客户端,此时,在页面上看到的信息和数据库中的信息不存在任何联系,而且所有的ADO.NET对象都被释放
一旦成功打开数据库连接,就可以编写代码来查看基本的连接信息,示例如下:

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace Sample12_1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入学生的姓名:");
            string name = Console.ReadLine();
            string selectSQL = "select * from students where StuName ='" + name +"'";
            // 定义ADO.NET对象.
            SqlConnection sqlConnection = CreateConnection();
            SqlCommand cmd = new SqlCommand(selectSQL, sqlConnection);
            SqlDataReader reader;

            try
            {
                sqlConnection.Open();//打开数据库
                reader = cmd.ExecuteReader();//从数据库中读取数据
                reader.Read();
                Console.WriteLine("学生{0}的基本信息:",name);
                Console.WriteLine("学号:{0}", reader["ID"]);
                Console.WriteLine("姓名:{0}", reader["StuName"]);
                Console.WriteLine("电话:{0}", reader["Phone"]);
                Console.WriteLine("地址:{0}", reader["Address"]);
                Console.WriteLine("城市:{0}", reader["City"]);
                Console.WriteLine("国家:{0}", reader["State"]);
            }
            catch (Exception err)
            {
                //连接不成功时显示连接错误
                Console.WriteLine("连接数据库错误:{0}", err.Message.ToString());

            }
            finally
            {
                //关闭数据库
                sqlConnection.Close();
                Console.WriteLine("前数据库连接:{0}", sqlConnection.State.ToString());
            }
            Console.ReadLine();
        }
        public static SqlConnection CreateConnection()
        {
            //数据库连接字符串
            //Data Source=book\\bookdb:数据库服务器
            //Initial Catalog=BookSample:要访问的数据库
            //User ID=sa:用户名
            //Password=123:密码
            string ConnectionString = "Data Source=book\\bookdb;Initial Catalog=BookSample;User ID=sa;Password=123";
            //创建数据库连接
            SqlConnection sqlConnection = new SqlConnection(ConnectionString);
            return sqlConnection;//返回创建的数据库连接
        }

    }
}

上面程序中声明了一个数据库连接对象,在try语句块中打开数据库连接并显示连接后连接信息状态,在catch块中捕捉打开连接时发生的错误,在finally中关闭数据库连接,并显示当前数据库连接的状态信息。
插入和更新数据可以按照如下步骤操作:
(1)创建Connection和Command对象
(2)执行SQL命令(插入或更新命令)
插入数据

View Code

更新数据

View Code

从数据库中读取信息

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionstring = "Data Source=ZKX-PC\\SQLEXPRESS;Initial Catalog=db_Student;User ID=sa;Password=123456";
            //Data Source=ZKX-PC\\SQLEXPRESS;要注意转义字符
            SqlConnection con = new SqlConnection(connectionstring);
            string sqlstring = "select * from tb_StuInfo  where stuID=1002";
            SqlCommand cmd = new SqlCommand(sqlstring, con);
            con.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            reader.Read();
            Console.WriteLine("序号:{0} ", reader["stuID"]);
            Console.WriteLine("姓名:{0} ", reader["stuName"]);
            Console.WriteLine("性别:{0} ", reader["stuSex"]);
            Console.WriteLine("兴趣:{0} ", reader["stuHobby"]);
            con.Close();            
        }
    }
}
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("请输入要查询学生的姓名");
            string stuname = Console.ReadLine();
            string connectionstring = "Data Source=ZKX-PC\\SQLEXPRESS;Initial Catalog=db_Student;User ID=sa;Password=123456";
            //Data Source=ZKX-PC\\SQLEXPRESS;要注意转义字符
            SqlConnection con = new SqlConnection(connectionstring);
            string sqlstring = "select * from tb_StuInfo  where stuName='"+stuname+"'";
            SqlCommand cmd = new SqlCommand(sqlstring, con);
            con.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            reader.Read();
            Console.WriteLine("序号:{0} ", reader["stuID"]);
            Console.WriteLine("姓名:{0} ", reader["stuName"]);
            Console.WriteLine("性别:{0} ", reader["stuSex"]);
            Console.WriteLine("兴趣:{0} ", reader["stuHobby"]);
           
             con.Close();
            
        }
    }
}

  
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("请输入要查询学生的姓名");
            string stuname = Console.ReadLine();
            string connectionstring = "Data Source=ZKX-PC\\SQLEXPRESS;Initial Catalog=db_Student;User ID=sa;Password=123456";
            //Data Source=ZKX-PC\\SQLEXPRESS;要注意转义字符
            SqlConnection con = new SqlConnection(connectionstring);
            string sqlstring = "select * from tb_StuInfo  where stuName='"+stuname+"'";
            SqlCommand cmd = new SqlCommand(sqlstring, con);
            con.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            reader.Read();
            Console.WriteLine("序号:{0} ", reader["stuID"]);
            Console.WriteLine("姓名:{0} ", reader["stuName"]);
            Console.WriteLine("性别:{0} ", reader["stuSex"]);
            Console.WriteLine("兴趣:{0} ", reader["stuHobby"]);
            con.Close();//必须先关闭再打开,否则会提示错误:已经有打开的与此Command相关联的DataReader,必须先将它关闭
            string sqlstring2 = "select * from tb_StuInfo where stuID='1001'";//stuName='小三',stuSex='男',stuHobby='无' where stuID=1002"
            SqlCommand cmd2 = new SqlCommand(sqlstring2, con);
            con.Open();
            reader = cmd2.ExecuteReader();
            reader.Read();
            Console.WriteLine("序号:{0} ", reader["stuID"]);
            Console.WriteLine("姓名:{0} ", reader["stuName"]);
            Console.WriteLine("性别:{0} ", reader["stuSex"]);
            Console.WriteLine("兴趣:{0} ", reader["stuHobby"]);
            con.Close();
            
        }
    }
}

  

 

不连接的数据访问

不连接的数据访问将会在内存中的DataSet对象中保存数据的副本,在数据库连接断开后仍然能够操作这些数据。不连接的数据访问方式并不是意味着不需要连接数据库,而是在连接数据库之后,把数据从数据库中取出把这些数据放入DataSet,然后断开数据库连接,这是虽然数据库连接断开了,但仍然可以对这些数据进行操作,不过由于数据库连接已经断开,因此对这些数据的操作将不会影响到数据库中的数据的状态。因此,如果需要修改数据库中的数据需要重新连接到数据库,把修改后的数据再写入数据库。

通过不连接数据库的方式从数据库获取数据,示例如下:

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace Sample12_2
{
    class Program
    {
        //变量dsPubs将存储从数据库中获得的数据
        private static DataSet dsPubs = new DataSet();
        static void Main(string[] args)
        {
            Console.WriteLine("请输入学生的姓名:");
            string name = Console.ReadLine();
            string selectSQL = "select * from students where StuName ='" + name + "'";
            // 定义ADO.NET对象.
            SqlConnection sqlConnection = CreateConnection();
            SqlCommand cmd = new SqlCommand(selectSQL, sqlConnection);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);

            try
            {
                sqlConnection.Open();//打开数据库
                //填充DataSet
                adapter.Fill(dsPubs, "Students");
                //关闭数据库
                sqlConnection.Close();
                Console.WriteLine("前数据库连接:{0}", sqlConnection.State.ToString());
                Console.WriteLine("学生{0}的基本信息:", name);
                Console.WriteLine("学号:{0}", dsPubs.Tables["Students"].Rows[0]["ID"]);
                Console.WriteLine("姓名:{0}", dsPubs.Tables[0].Rows[0]["StuName"]);
                Console.WriteLine("电话:{0}", dsPubs.Tables[0].Rows[0]["Phone"]);
                Console.WriteLine("地址:{0}", dsPubs.Tables[0].Rows[0]["Address"]);
                Console.WriteLine("城市:{0}", dsPubs.Tables[0].Rows[0]["City"]);
                Console.WriteLine("国家:{0}", dsPubs.Tables[0].Rows[0]["State"]);
            }
            catch (Exception err)
            {
                //连接不成功时显示连接错误
                Console.WriteLine("连接数据库错误:{0}", err.Message.ToString());

            }
            finally
            {
                ////关闭数据库
                //sqlConnection.Close();
                //Console.WriteLine("前数据库连接:{0}", sqlConnection.State.ToString());
            }
            Console.ReadLine();
        }
        public static SqlConnection CreateConnection()
        {
            //数据库连接字符串
            //Data Source=book\\bookdb:数据库服务器
            //Initial Catalog=BookSample:要访问的数据库
            //User ID=sa:用户名
            //Password=123:密码
            string ConnectionString = "Data Source=book\\bookdb;Initial Catalog=BookSample;User ID=sa;Password=123";
            //创建数据库连接
            SqlConnection sqlConnection = new SqlConnection(ConnectionString);
            return sqlConnection;//返回创建的数据库连接
        }
    }
}

自己的:

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;//DataSet

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {//不连接的数据访问,注意与直接数据访问的区别
            Console.Write("请输入要查询学生的姓名");
            string stuname = Console.ReadLine();
            string connectionstring = "Data Source=ZKX-PC\\SQLEXPRESS;Initial Catalog=db_Student;User ID=sa;Password=123456";
            //Data Source=ZKX-PC\\SQLEXPRESS;要注意转义字符
            SqlConnection con = new SqlConnection(connectionstring);
            string sqlstring = "select * from tb_StuInfo  where stuName='"+stuname+"'";
            SqlCommand cmd = new SqlCommand(sqlstring, con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            con.Open();
            DataSet ds = new DataSet();
            da.Fill(ds,"tb_StuInfo");
            con.Close();
            Console.WriteLine("数据库连接已经关闭!");
            Console.WriteLine("序号:{0} ", ds.Tables["tb_StuInfo"].Rows[0]["stuID"]);
            Console.WriteLine("姓名:{0} ", ds.Tables["tb_StuInfo"].Rows[0]["stuName"]);
            Console.WriteLine("性别:{0} ", ds.Tables["tb_StuInfo"].Rows[0]["stuSex"]);
            Console.WriteLine("兴趣:{0} ", ds.Tables["tb_StuInfo"].Rows[0]["stuHobby"]);                
        }
    }
}

  

 

posted @ 2012-11-22 23:06  .NET~莫愁  阅读(356)  评论(0编辑  收藏  举报