欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C# - [窗体] Login 数据库账号登录检测

程序员文章站 2022-05-08 17:04:17
...

▶ 窗体界面

C# - [窗体] Login 数据库账号登录检测

▶ 源码

using System;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace login_demo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.AutoSizeMode = AutoSizeMode.GrowAndShrink;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            checkLogin();
        }

        /// <summary>
        /// 按钮点击逻辑处理模块
        /// </summary>
        void checkLogin()
        {
            String conn_str = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=E:\Desktop\C-Sharp\Month_11\day1115\login_demo\login_demo\Database1.mdf;Integrated Security=True";
            SqlConnection conn = new SqlConnection(conn_str);
            SqlDataReader sql_reader = null;

            String raw_username = username_textBox.Text.Trim();
            String raw_password = password_textBox.Text.Trim();

            //数据库连接
            try
            {
                conn.Open();
                String sql_1 = $"SELECT * FROM ACCOUNT WHERE username='{raw_username}'";
                var sql_command = new SqlCommand(sql_1, conn);
                sql_reader = sql_command.ExecuteReader();
                if (!sql_reader.Read())
                {
                    MessageBox.Show("Account Not Exists!", "Warnning Info!");
                }
                else if(sql_reader.GetString(1)!=raw_password)
                {
                    MessageBox.Show("Password Error!","Warnning Info!");
                }
                else
                {
                    MessageBox.Show("Login Successfully!","Tips");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Warnning Info!");
            }
            finally
            {
                sql_reader.Close();
                conn.Close();
            }
        }
    }
}