ADO.NET_02

一、说明

这个例子是小白跟着学习代码记录,模拟用户登陆功能,并可以查询所有学生信息。

 

二、代码

共4个文件,如下

App.config

"1.0" encoding="utf-8" ?>

  
    "MyschoolConnectionString" connectionString="Data Source=.;Initial Catalog=Mydata;Persist Security Info=True;User ID=XLJ;Pooling=False;MultipleActiveResultSets=False;Encrypt=False;TrustServerCertificate=True;Password=123456;" />
  
  
    "v4.0" sku=".NETFramework,Version=v4.7" />
  

 

Student.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ado.NETDemo2
{
    /// 
    /// 学生实体类
    /// 
    public class Student
    {
        /// 
        /// 编号
        /// 
        public string StudentNo { get; set; }
        
        /// 
        /// 姓名
        /// 
        public string StudentName { get; set; }
    }
}

 

StudentDao.cs

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ado.NETDemo2
{
    public class StudentDao
    {
        // 1、编写连接字符串
        //string connectionString = "server=.;uid=XLJ;pwd=123456;database=Mydata;";
        //string connectionString = "Data Source=.;Initial Catalog=Mydata;Persist Security Info=True;User ID=XLJ;Pooling=False;MultipleActiveResultSets=False;Encrypt=False;TrustServerCertificate=True;Password=123456;";
        public static string connectionString = ConfigurationManager.ConnectionStrings["MyschoolConnectionString"].ToString();

        // 2、建立连接
        SqlConnection connection = new SqlConnection(connectionString);
        // connection.ConnectionString = connectionString;

        /// 
        /// 验证用户是否存在
        /// 
        /// 
        /// 
        /// 
        /// 
        public bool ValidataUser(string userName, string password, ref string message)
        {
            

            bool result = false;
            try
            {
                // 3、打开连接
                connection.Open();
                // Console.WriteLine("连接打开成功");

                // 4、实现登陆功能
                SqlCommand command = new SqlCommand();
                //command.CommandText = string.Format("select count(*) from Student where StudentName='{0}' and LoginPwd='{1}'", userName, userPwd);
                //command.CommandText = $"select count(*) from Student where StudentName='{userName}' and LoginPwd='{password}'";
                StringBuilder sb = new StringBuilder("select count(*) from Student");
                sb.AppendFormat(" where StudentName='{0}' and LoginPwd='{1}'", userName, password);
                command.CommandText = sb.ToString();
                command.Connection = connection;

                // 5、执行命令
                int num = (int)command.ExecuteScalar();
                if (num > 0)
                {
                    result = true;
                    message = "登陆成功";
                }
                else
                {
                    message = "用户名或者密码有误";
                }
                
            }
            catch (SqlException sqlException)
            {
                Console.WriteLine("数据库访问异常~" + sqlException.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("程序出现问题,请联系管理员。" + ex.Message);
            }
            finally
            {
                // 6、关闭连接
                connection.Close();
                //Console.WriteLine("连接关闭成功");
            }

            return result;
        }

        /// 
        /// 实现登陆获取邮箱
        /// 
        /// 
        /// 
        /// 
        public string Login(string userName, string password)
        {
            // 2、建立连接
            SqlConnection connection = new SqlConnection(connectionString);
            // connection.ConnectionString = connectionString;

            string result = string.Empty;
            try
            {
                // 3、打开连接
                connection.Open();
                // Console.WriteLine("连接打开成功");

                // 4、实现登陆功能
                SqlCommand command = new SqlCommand();
                //command.CommandText = string.Format("select count(*) from Student where StudentName='{0}' and LoginPwd='{1}'", userName, userPwd);
                command.CommandText = $"select * from Student where StudentName='{userName}' and LoginPwd='{password}'";
                command.Connection = connection;

                // 5、执行命令
                SqlDataReader reader = command.ExecuteReader();
                reader.Read();
                result = reader["email"].ToString();
            }
            catch (SqlException sqlException)
            {
                Console.WriteLine("数据库访问异常~" + sqlException.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("程序出现问题,请联系管理员。" + ex.Message);
            }
            finally
            {
                // 6、关闭连接
                connection.Close();
                //Console.WriteLine("连接关闭成功");
            }

            return result;
        }

        /// 
        /// 获取所有学生
        /// 
        /// 
        public List GetStudentList()
        {
            List students = new List();

            StringBuilder sql = new StringBuilder("select StudentNo,StudentName from Student");

            // 打开连接
            connection.Open();

            SqlCommand command = new SqlCommand(sql.ToString(), connection);
            SqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                Student student = new Student();
                student.StudentNo = reader["StudentNo"].ToString();
                student.StudentName = reader["StudentName"].ToString();

                // 组装到学生集合列表中
                students.Add(student);
            }
            // 关闭读取器
            reader.Close();

            // 关闭连接
            connection.Close();
            return students;
        }
    }
}

 

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ado.NETDemo2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入用户名^_^");
            string userName = Console.ReadLine();
            Console.WriteLine("请输入密码o(* ̄︶ ̄*)o");
            string userPwd = Console.ReadLine();

            StudentDao dao = new StudentDao();
            string msg = string.Empty;

            if (dao.ValidataUser(userName, userPwd, ref msg))
            {
                string email = dao.Login(userName, userPwd);
                Console.WriteLine("恭喜{0},{1}", email, msg);

                // 选择
                Console.WriteLine("请选择");
                int choice = int.Parse(Console.ReadLine());

                switch (choice)
                {
                    case 1:
                        Console.WriteLine("统计学生人数");
                        break;
                    case 2:
                        Console.WriteLine("查询学生名单");
                        List students = dao.GetStudentList();
                        foreach (var student in students)
                        {
                            Console.WriteLine(student.StudentName + "————" + student.StudentNo);
                        }
                        break;
                    default:
                        break;
                }
            }
            else
            {
                Console.WriteLine(msg);
            }
        }
    }
}

 

三、效果

ADO.NET_02_第1张图片

 

你可能感兴趣的:(ADO.NET_02)