一、说明

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

二、代码

共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);
}
}
}
}

三、效果

最新文章

  1. 设置apache登陆密码验证
  2. bs4 python解析html
  3. 最小安装模式下Centos7.*网卡启动配置
  4. Drupal 7.31 SQL注入漏洞利用具体解释及EXP
  5. 1008: [HNOI2008]越狱
  6. 转:Node.js软肋之CPU密集型任务
  7. thrift TNonblockingServer 使用
  8. ASP.NET MVC开发学习过程中遇到的细节问题以及注意事项
  9. IDEA + Maven + JavaWeb项目搭建
  10. Spark源码剖析(六):Worker原理与源码剖析
  11. dedecms内容页调用图片集文档的图集图片
  12. html5学习之旅第一篇
  13. C#图解教程
  14. java 中的打印流
  15. C语言--isspace()函数实现
  16. WPS处理个人信息一种方法
  17. DirectX全屏游戏中弹出窗口(转)
  18. 【转】C/C++ 函数指针与类函数指针
  19. 时间插件WdatePicker使用方法
  20. HDUOJ-----2824The Euler function

热门文章

  1. (5)连续非周期信号的傅里叶变换(频谱) &amp; 周期信号的傅里叶变换
  2. 【html、CSS、javascript-12】jquery-效果
  3. TZ_14_Zuul网关
  4. python twisted 的定时调用带参的函数
  5. 关于python 环境变量
  6. Sessions 与Cookies详解
  7. mysql连接出现Unknown system variable &#39;tx_isolation&#39;异常
  8. Python 数据文件操作——写出数据
  9. 用两个栈实现队列功能【剑指offer】
  10. RSA 2019安全大会:企业资产管理成行业新风向标,云上安全占优势