ADO.NET_01

Posted xulinjun

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ADO.NET_01相关的知识,希望对你有一定的参考价值。

一、说明

这个例子是小白跟着学习代码记录,模拟用户登陆功能,提示用户输入用户名及密码,然后与数据库里的用户数据进行比对,成功就返回成功提示及邮箱,失败,则失败提示。

 

二、代码

共3个文件,如下。

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
      <add name="MyschoolConnectionString" connectionString="Data Source=.;Initial Catalog=Mydata;Persist Security Info=True;User ID=XLJ;Pooling=False;MultipleActiveResultSets=False;Encrypt=False;TrustServerCertificate=True;Password=123456;" />
    </connectionStrings>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7" />
    </startup>
</configuration>

 

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.NETDemo

    public class StudentDao
    
        /// <summary>
        /// 验证用户是否存在
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool ValidataUser(string userName, string password, ref string message)
        
            // 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;";
            string connectionString = ConfigurationManager.ConnectionStrings["MyschoolConnectionString"].ToString();

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

            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‘";
                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;
        

        /// <summary>
        /// 实现登陆获取邮箱
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public string Login(string userName, string password)
        
            // 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;";
            string connectionString = ConfigurationManager.ConnectionStrings["MyschoolConnectionString"].ToString();

            // 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;
        
    

 

Program.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.NETDemo

    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);
            
            else
            
                Console.WriteLine(msg);
            
        
    

 

三、效果

技术图片

 

对应的数据库如下:

技术图片

 

以上是关于ADO.NET_01的主要内容,如果未能解决你的问题,请参考以下文章

.NET基础操作回顾_使用ADO.NET操作SqlServer使用的类

ADO.NET 实体框架与 NHibernate [关闭]

ADO.NET - Size 属性的大小为 0 无效

如何提高 ADO.NET 中大量 INSERT 的速度?

带有 ADO .NET 的 ASP .NET MVC 会导致问题吗?

ADO.Net 数据库查询