一、说明

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

二、代码

共4个文件,如下

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>

Student.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace Ado.NETDemo2
{
/// <summary>
/// 学生实体类
/// </summary>
public class Student
{
/// <summary>
/// 编号
/// </summary>
public string StudentNo { get; set; } /// <summary>
/// 姓名
/// </summary>
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; /// <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)
{ 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 > )
{
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)
{
// 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;
} /// <summary>
/// 获取所有学生
/// </summary>
/// <returns></returns>
public List<Student> GetStudentList()
{
List<Student> students = new List<Student>(); 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 :
Console.WriteLine("统计学生人数");
break;
case :
Console.WriteLine("查询学生名单");
List<Student> 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对象的详解

    1. Connection 类 和数据库交互,必须连接它.连接帮助指明数据库服务器.数据库名字.用户名.密码,和连接数据库所需要的其它参数.Connection对象会被Command对象使用,这样就能 ...

  2. WebForm获取GET或者POST参数到实体的转换,ADO.NET数据集自动转换实体

    最近在修改维护以前的webform项目(维护别人开发的.....)整个aspx没有用到任何的控件,这个我也比较喜欢不用控件所以在提交信息的时候需要自己手动的去Request.QueryString[] ...

  3. ADO.NET编程之美----数据访问方式(面向连接与面向无连接)

    最近,在学习ADO.NET时,其中提到了数据访问方式:面向连接与面向无连接.于是,百度了一下,发现并没有很好的资料,然而,在学校图书馆中发现一本好书(<ASP.NET MVC5 网站开发之美&g ...

  4. ADO.NET一小记-select top 参数问题

    异常处理汇总-后端系列 http://www.cnblogs.com/dunitian/p/4523006.html 最近使用ADO.NET的时候,发现select top @count xxxx 不 ...

  5. .NET基础拾遗(6)ADO.NET与数据库开发基础

    Index : (1)类型语法.内存管理和垃圾回收基础 (2)面向对象的实现和异常的处理 (3)字符串.集合与流 (4)委托.事件.反射与特性 (5)多线程开发基础 (6)ADO.NET与数据库开发基 ...

  6. 升讯威ADO.NET增强组件(源码):送给喜欢原生ADO.NET的你

    目前我们所接触到的许多项目开发,大多数都应用了 ORM 技术来实现与数据库的交互,ORM 虽然有诸多好处,但是在实际工作中,特别是在大型项目开发中,容易发现 ORM 存在一些缺点,在复杂场景下,反而容 ...

  7. ADO.NET Entity Framework 在哪些场景下使用?

    在知乎回答了下,顺手转回来. Enity Framework已经是.NET下最主要的ORM了.而ORM从一个Mapping的概念开始,到现在已经得到了一定的升华,特别是EF等对ORM框架面向对象能力的 ...

  8. ADO.NET 核心对象简介

    ADO.NET是.NET中一组用于和数据源进行交互的面向对象类库,提供了数据访问的高层接口. ADO.NOT类库在System.Data命名空间内,根据我们访问的不同数据库选择命名空间,System. ...

  9. ODBC、OLE DB、 ADO的区别

    转自:http://blog.csdn.net/yinjingjing198808/article/details/7665577 一.ODBC ODBC的由来 1992年Microsoft和Syba ...

随机推荐

  1. Luogu P1273 有线电视网(树形dp+背包)

    P1273 有线电视网 题面 题目描述 某收费有线电视网计划转播一场重要的足球比赛.他们的转播网和用户终端构成一棵树状结构,这棵树的根结点位于足球比赛的现场,树叶为各个用户终端,其他中转站为该树的内部 ...

  2. 【html、CSS、javascript-1】html基础

    HTML   翻译成代码如下: web: import socket def handle_request(client): buf = client.recv(1024) client.sendal ...

  3. 通过游戏学python 3.6 第一季 第八章 实例项目 猜数字游戏--核心代码--猜测次数--随机函数和屏蔽错误代码--优化代码及注释--简单账号密码登陆--账号的注册查询和密码的找回修改--锁定账号--锁定次数

    通过游戏学python 3.6 第一季 第八章 实例项目 猜数字游戏--核心代码--猜测次数--随机函数和屏蔽错误代码--优化代码及注释--简单账号密码登陆--账号的注册查询和密码的找回修改--锁定账 ...

  4. PHP--http_build_query--把数组化成&key=value方式

  5. git学习记录——远程仓库(说白了就是代码放到githup上)

    远程仓库 现在讲述的这些SVN都已经做到了,并没什么稀奇的地方 所以这节课赘述的是杀手级的东西——远程仓库githup ssh-keygen -t rsa  -C "xxxxxxxxxxx@ ...

  6. IoT: 物联网安全测试经验总结

    前言 今年早些时候,我参与了许多关于物联网解决方案的安全测试.主要目标是找出体系结构和解决方案中的漏洞.在这篇文章中,我将讨论一些与物联网解决方案的问题和挑战. 什么是物联网? 在你学习有关IPv6的 ...

  7. 沙雕去死吧! 劳资终于弄好了toimcat9 apt和ssl配置

    搜一下吧,要不就是不用apr模式,也不用nio模式,直接用bio模式跑的,麻烦问一下,您们都是傻屌吗? APR模式必须要用!!!!! 然后全他妈的用jks证书,然后再提取公钥*.cer,然后再转换为* ...

  8. tumblr arch information

    http://developer.51cto.com/art/201305/395757.htm 每月超过30%的增长当然不可能没有挑战,其中可靠性问题尤为艰巨.每天5亿次浏览量,峰值每秒4万次请求, ...

  9. 数据库设计 ch.7

    数据库建设的基本规律 三分技术 七分管理 十二分基础数据 阶段 需求分析阶段 概念设计阶段 逻辑设计阶段 物理设计阶段 数据库实施阶段 数据库维护阶段 1 需求分析 2 概念设计 形成概念模型 3 逻 ...

  10. 手机号测吉凶python代码

    根据数理数来测电话后四位吉凶: 数理数 解释批注 0点特殊.......大吉 1大展鸿图.可获成功吉 2一盛一衰.劳而无功凶 3蒸蒸日上.百事顺遂吉 4坎坷前途.苦难折磨凶 5生意欣荣.名利双收吉 6 ...