一、说明

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

二、代码

共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. 10分钟完成 mongodb replSet 部署

    开始: ------------------------------------------------------------------------------------------------ ...

  2. 在C#应用中使用Common Logging日志接口

    我在C#应用中一般使用log4net来记录日志,但如果项目中有个多个工程,那么没有工程都需要引用log4neg,感觉很不爽.不过今日在开spring.net的时候,看到了有个通用日志接口Common ...

  3. [jnhs]教训之jsp页面无法用jstl取值的坑.真他妈的奇葩,实体类的属性名不能用大写

    结果页面永远都是空 调试发现,数据正常的塞进去了 问题解决: https://zhidao.baidu.com/question/570584436.html 实体类的属性名,首字母不能大写,改成小写 ...

  4. jnhs-java实体类的有参构造器 无参构造器Could not instantiate bean class 实体类No default constructor found

    new一个对象的时候要用到构造函数, 例如Hello hello = new Hello();这时调用的是Hello的无参数构造方法; Hello hello = new Hello("hi ...

  5. spring JdbcTemplate最基本的使用

    package com.com.jdbctemplate; import org.springframework.jdbc.core.JdbcTemplate; import org.springfr ...

  6. 用js控制video的src_百度知道

    代码如下 <section id="player"> <video id="media" width="100%" hei ...

  7. 优化 Tengine HTTPS 握手时间

    背景 网络延迟是网络上的主要性能瓶颈之一.在最坏的情况下,客户端打开一个链接需要DNS查询(1个 RTT),TCP握手(1个 RTT),TLS 握手(2个RTT),以及最后的 HTTP 请求和响应,可 ...

  8. 快速排序的一种实现(Mark Allen 数据结构与算法 c语言版)

    之前关于快速排序一直比较模糊,网上有几种常见写法: 方法一: void quickSort(int s[], int l, int r) { if (l< r) { int i = l, j = ...

  9. SDUT-3404_数据结构实验之排序七:选课名单

    数据结构实验之排序七:选课名单 Time Limit: 1000 ms Memory Limit: 65536 KiB Problem Description 随着学校规模的扩大,学生人数急剧增加,选 ...

  10. BZOJ 3057圣主的考验题解

    老师居然考这么毒瘤的题目!!!!! 很容易想到dp,f[i][j]表示有i个节点,左子树的最深深度为j的方案数 枚举左子树有多少节点然后转移,复杂度为n^3 T飞~ 我们考虑到有深度为h的树的节点有多 ...