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 ...
随机推荐
- MySQL事务、锁机制、查询缓存
MySQL事务 何为事务? 事务(Transaction)是访问并可能更新数据库中各种数据项的一个程序执行单元(unit). 一个事务可以是一条SQL语句,一组SQL语句或整个程序. 事务的特性: 事 ...
- 用户测评 | EDAS Serverless 上手体验
背景 最初, 是因为对 Serverless 这一概念感兴趣, 所以开始试用阿里云函数计算,使用过程中感受到了函数计算快速.按需付费和弹性伸缩等方面的优势,随后我在天气预报.发送短信等场景下开始了更深 ...
- 洛谷2593 [ZJOI2006]超级麻将——可行性dp
题目:https://www.luogu.org/problemnew/show/P2593 发现三个连续牌的影响范围只有3.相同牌的影响范围只有1之后就可以dp了. O(100^7)T飞. #inc ...
- Java review-basic2
1.Implement a thread-safe (blocking) queue: Class Producer implements Runable{ Private final Blockin ...
- cookie记录
登录页面引用: <script src="/jquery.cookie.js"></script> 登录页面jq: var telphone = $('[n ...
- vue跨域,复杂请求,后端为beego
关于跨域,网上讲得很多,具体实施起来大多讲的不详细,贴我的vue端代码 require('es6-promise').polyfill() import fetch from 'isomorphic- ...
- win10 下安装 neo4j
1.neo4j介绍 neo4j是基于Java语言编写图形数据库.图是一组节点和连接这些节点的关系.图形数据库也被称为图形数据库管理系统或GDBMS.详细介绍可看Neo4j 教程 2.安装Java jd ...
- BZOJ2069: [POI2004]ZAW
2069: [POI2004]ZAW Time Limit: 10 Sec Memory Limit: 64 MBSubmit: 303 Solved: 138[Submit][Status][D ...
- JavaScript实现无缝滚动 原理详细讲解
先了解一下对象的几个的属性: innerHTML: 设置或获取位于对象起始和结束标签内的 HTML scrollHeight: 获取对象的滚动高度. scrollLeft: 设置或获取位于对象左边界和 ...
- 说说a标签的onclick和href
在平时我们一般会在列表中的最后一列给加上操作功能,一般的操作功能是修改和删除,这个操作我们可以通过a标签来实现其功能. <a class="pn-opt" href=&quo ...