标签:scalar sele open oid demo 用户名 对象 pac lse
1、创建ConnectionDB类
存储连接数据库,关闭数据库
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Demo { class ConnectionDB { //准备连接字符串 static string str = "Data Source=.;Initial Catalog=MySchool;User ID=sa;Pwd=1"; //准备连接对象 public SqlConnection con = new SqlConnection(str); //连接数据库 public void OpenDB() { try { con.Open(); } catch (Exception ex) { Console.WriteLine("发生异常:"+ex); } } //关闭数据库 public void CloseDB() { con.Close(); } } }
2、创建User类
存储登录方法
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Demo { class User { ConnectionDB db = new ConnectionDB(); //登录方法 public void Login(string loginID, string loginPwd) { //步骤一:创建一个Command对象 string sql = "SELECT COUNT(1) FROM Login WHERE LoginID=‘" + loginID + "‘ AND Loginpwd=‘" + loginPwd + "‘"; Console.WriteLine(sql); //打开数据库连接 db.OpenDB(); SqlCommand cmd = new SqlCommand(sql, db.con); //步骤二:接收数据库返回值 int count = (int)cmd.ExecuteScalar(); //步骤三:判断返回值 if (count>0) { Console.WriteLine("登录成功"); } else { Console.WriteLine("登录失败"); } } } }
3、Main方法测试
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namespace Demo { class Program { static void Main(string[] args) { #region 连接数据库 //步骤一:配置参数 string conn = "Data Source=.;Initial Catalog=MySchool;User ID=sa;Pwd=."; //步骤二:创建对象并连接数据库 SqlConnection co = new SqlConnection(conn); //步骤三:打开数据库 //co.Open(); //Console.WriteLine("打开数据库连接成功!"); //步骤N:关闭数据库 //co.Close(); //Console.WriteLine("关闭数据库连接成功!"); #endregion #region 处理异常 try { co.Open(); Console.WriteLine("打开数据库连接成功!"); } catch (SqlException ex) { Console.WriteLine("异常:" + ex); } finally { Console.WriteLine("永远都在你身边!"); } #endregion #region 登录 Console.WriteLine("请输入用户名:"); string loginID = Console.ReadLine(); Console.WriteLine("请输入密码:"); string loginpwd = Console.ReadLine(); User user = new User(); user.Login(loginID, loginpwd); #endregion Console.ReadLine(); } } }
标签:scalar sele open oid demo 用户名 对象 pac lse
原文地址:https://www.cnblogs.com/Zzzzn/p/10169841.html