ADO.NET_02
一、说明
这个例子是小白跟着学习代码记录,模拟用户登陆功能,并可以查询所有学生信息。
二、代码
共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的更多相关文章
- ADO.NET对象的详解
1. Connection 类 和数据库交互,必须连接它.连接帮助指明数据库服务器.数据库名字.用户名.密码,和连接数据库所需要的其它参数.Connection对象会被Command对象使用,这样就能 ...
- WebForm获取GET或者POST参数到实体的转换,ADO.NET数据集自动转换实体
最近在修改维护以前的webform项目(维护别人开发的.....)整个aspx没有用到任何的控件,这个我也比较喜欢不用控件所以在提交信息的时候需要自己手动的去Request.QueryString[] ...
- ADO.NET编程之美----数据访问方式(面向连接与面向无连接)
最近,在学习ADO.NET时,其中提到了数据访问方式:面向连接与面向无连接.于是,百度了一下,发现并没有很好的资料,然而,在学校图书馆中发现一本好书(<ASP.NET MVC5 网站开发之美&g ...
- ADO.NET一小记-select top 参数问题
异常处理汇总-后端系列 http://www.cnblogs.com/dunitian/p/4523006.html 最近使用ADO.NET的时候,发现select top @count xxxx 不 ...
- .NET基础拾遗(6)ADO.NET与数据库开发基础
Index : (1)类型语法.内存管理和垃圾回收基础 (2)面向对象的实现和异常的处理 (3)字符串.集合与流 (4)委托.事件.反射与特性 (5)多线程开发基础 (6)ADO.NET与数据库开发基 ...
- 升讯威ADO.NET增强组件(源码):送给喜欢原生ADO.NET的你
目前我们所接触到的许多项目开发,大多数都应用了 ORM 技术来实现与数据库的交互,ORM 虽然有诸多好处,但是在实际工作中,特别是在大型项目开发中,容易发现 ORM 存在一些缺点,在复杂场景下,反而容 ...
- ADO.NET Entity Framework 在哪些场景下使用?
在知乎回答了下,顺手转回来. Enity Framework已经是.NET下最主要的ORM了.而ORM从一个Mapping的概念开始,到现在已经得到了一定的升华,特别是EF等对ORM框架面向对象能力的 ...
- ADO.NET 核心对象简介
ADO.NET是.NET中一组用于和数据源进行交互的面向对象类库,提供了数据访问的高层接口. ADO.NOT类库在System.Data命名空间内,根据我们访问的不同数据库选择命名空间,System. ...
- ODBC、OLE DB、 ADO的区别
转自:http://blog.csdn.net/yinjingjing198808/article/details/7665577 一.ODBC ODBC的由来 1992年Microsoft和Syba ...
随机推荐
- Leetcode221. Maximal Square最大正方形
在一个由 0 和 1 组成的二维矩阵内,找到只包含 1 的最大正方形,并返回其面积. 示例: 输入: 1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0 输出: 4 方法一 ...
- CentOS 6.5之zabbix2.2的简单部署
Zabbix是一个基于WEB界面的提供分布式系统监视以及网络监视功能的企业级的开源解决方案.(目前,官方长期维护的稳定版本有2.2和3.0) 其他常见的监控工具还有: (1)Cacti:Cacti是一 ...
- 超干货!Cassandra Java堆外内存排查经历全记录
背景 最近准备上线cassandra这个产品,同事在做一些小规格ECS(8G)的压测.压测时候比较容易触发OOM Killer,把cassandra进程干掉.问题是8G这个规格我配置的heap(Xmx ...
- 爬取简书图片(使用BeautifulSoup)
import requests from bs4 import BeautifulSoup url_list = [] kv = {'User-Agent':'Mozilla/5.0'} r = re ...
- php数字转人民币金额大写
numToRmb.php <?php header("content-type:text/html;charset=utf-8"); function numToRmb($n ...
- 2019.10.20 csp-s模拟测试 lrd试题 反思总结
赶进度赶进度,丢个代码两三句备注一下完事了. day1: 前面两道题没实际写代码怕印象不深所以描述一下大意. T1: 题目大意:给出两个数&.|.^的结果(可能只给出其中某一项或者某两项),求 ...
- 【CodeVS】【2004年NOIP全国联赛提高组】1057 津津的储蓄计划
1057 津津的储蓄计划 2004年NOIP全国联赛提高组 时间限制: 1 s 空间限制: 128000 KB 题目等级 : 青铜 Bronze 题目描述 Description 津津的零花钱一直都是 ...
- JavaScript远程调用
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- Wndows下Apache+php+Mysql环境的搭建及其涉及的知识
一.安装Apache 1. 在网上搜索以下3个文件,以及找一个地方新建一个文件夹 好吧,这里有下载链接:http://pan.baidu.com/s/1hr9IdSS 文件夹内有:apache,mys ...
- web前端学习(三)css学习笔记部分(7)-- 文字和字体相关样式、盒子相关样式、背景与边框相关样式
12. 文字和字体相关样式 12.1 CSS3 给文字添加阴影 使用 text-shadow 属性给页面上的文字添加阴影效果,text-shadow 属性是在CSS2中定义的,在 CSS2.1 中 ...