从数据库中获取数据来验证登录信息…

--------------------------------几种情况的运行效果图--------------------------------------------
从数据库中获取数据来验证登录信息(有详细的注释)

从数据库中获取数据来验证登录信息(有详细的注释)

从数据库中获取数据来验证登录信息(有详细的注释) 从数据库中获取数据来验证登录信息(有详细的注释)
-------------------------------------代码------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;//导入SQL包
namespace QQ
{
    class DBHelper
    {
        ///
        /// QQ登录检查
        ///
        /// 用户名
        /// 用户密码
        ///
        public bool LoginCheck(string username,string userpwd) 
        {
            //将SqlConnection的对象connection设为成员变量
            SqlConnection connection = null;
            //定义一个bool类型的变量,用于return
            bool flag = true;
            try
            {
                //编写连接字符串,用于连接服务器
                string conStr = "Data Source=.;Initial Catalog=QQ;User ID = sa ; Pwd=123";
                //实例化一个连接对象
                connection = new SqlConnection(conStr);
                //打开服务器
                connection.Open();
                Console.WriteLine("服务器已经打开");
                //编写sql语句,用于检查qq服务器里有没有该用户
                string login = "select count(*) from qquser where qqid='" + username + "' and password='" + userpwd + "'";
                //编写SqlCommand对象,用于在数据库了查找用户
                SqlCommand command = new SqlCommand(login, connection);//里面有两个参数,第一个参数是SQL语句,用于在数据库查找;
                //第二个是sqlconnection对象,用于指定在那个数据库中查找
                int result = (int)command.ExecuteScalar();//用于接受sql语句查询的结果,count(*)为1说明查到唯一用户
                if (result == 1)
                {
                    Console.WriteLine("登录成功");
                }
                else
                {
                    Console.WriteLine("登录失败");
                    flag = false;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("异常捕获机制,该异常为:" + ex.Message);
                connection.Close();
            }
            //为了节约资源,用完后将数据库关闭
            finally 
            {
                connection.Close();
                Console.WriteLine("为了节约资源,服务器已经关闭");
            }
            return flag;
        }
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值