使用ADO.NET访问数据库

一.ADO.NET :用于连接数据库的技术

        1.ADO.NET分为两大组件

            DataSet:数据集

            .NET FRAMWORK :用于连接到数据库,发送命令,检索结果

        2.ADO.NET四大核心对象
            Connection
            Command
            DataAdapter
            DataReader

    二.使用ADO.NET访问数据库

        1.首先导入命名空间System.Data.SqlClient

        2.创建连接字符串

            String constr="Data Source=.;Initial Catalog=SchoolDB;User=sa;Password=.";
            如果没有密码password参数可以省略

        3.创建SqlConnection连接对象

            SqlConnection con=new SqlConnection(constr);

        4.打开数据库连接

            con.Open();

            在使用数据库之前要保证数据库连接是打开的

            con.Close();

            使用完数据库之后要关闭连接,释放资源

    三.捕获异常

        try{
                //将可能会发生异常的代码放入到try中

        }catch(异常类型)
                //如果try块发生异常,并且异常类型和catch块所捕获的异常类型相匹配,那么会执行catch
        {

        }finally{
                //无论任何情况都会走到finally块
        }
        捕获异常可以将异常捕获到,而不会导致程序的停止

    四.向数据库发送命令

        1.创建SQL语句

             String sql="select count(*) from Student Where StudentName='"+username+"' and Password='"+Password+"'";

        2.使用Command对象发送SQL命令

             SqlCommand com=new SqlCommand(sql,con);

        3.接收命令执行结果

             int count=(int)com.ExecuteScalar();

             ExecuteNonQuery()    执行不返回行的语句,如UPDATE等
             ExecuteReader()    返回DataReader对象
             ExecuteScalar()    返回单个值,如执行带COUNT(*)的SQL语句

        4.登录案例

            public bool ValidateUser() {
                bool falg=true;
                String constr = "Data Source=.;Initial Catalog=SchoolDB;User=sa;Password=.";
                SqlConnection con = new SqlConnection(constr);
                try
                {
                    //打开连接
                    con.Open();
                    Console.WriteLine("请输入用户名:");
                    string username=Console.ReadLine();
                    Console.WriteLine("请输入密码:");
                    string password = Console.ReadLine();
                    //1.编写SQL
                    string sql = "select count(*) from Student where StudentName='"+username+"' and LoginPwd='"+password+"'";
                    //2.创建Command对象
                    SqlCommand com = new SqlCommand(sql,con);
                    int count=(int)com.ExecuteScalar();
                    if (count > 0)
                    {
                    }
                    else {
                        falg = false;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);

                }
                finally {
                    con.Close();
                }
                return falg;
            }

原文地址:https://www.cnblogs.com/chx9832/p/9381475.html