【问题标题】:Check if username exists in database or not检查用户名是否存在于数据库中
【发布时间】:2021-12-15 22:28:00
【问题描述】:

如何检查给定的用户名是否存在于数据库中?

我需要程序在用户按下注册按钮时显示用户名是否存在,因为目前如果我输入一个现有的用户名,我的程序会出错并崩溃。

我的表名为Login,插入表有UsernamePassword

代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;

namespace Proton_System
{
    public partial class Register : Form
    {
        public Register()
        {
            InitializeComponent();
        }

        SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\baich\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30");
        SqlCommand cmd;

        private void buttonRegister_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "")
            {
                MessageBox.Show("Username or Password fields are empty", "Register Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (textBox2.Text == textBox3.Text)
            {
                con.Open();

                cmd = new SqlCommand ("INSERT INTO Login VALUES ('" + textBox1.Text + "', '" + textBox2.Text + "')", con);
                cmd.ExecuteNonQuery();

                MessageBox.Show("Your account has been successfully created", "Register Successful", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Password does not match", "Register Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Login Form1 = new Login();
            Form1.Show();
            this.Hide();
        }
    }
}

【问题讨论】:

  • 使用参数化查询或将数据库暴露给 SQL 注入攻击。
  • 我建议您使用好的身份验证库,而不是将密码存储在数据库中并以纯文本形式存储。至少对密码进行哈希处理。
  • select count(yourusernamefield) from login where yourusernamefield = ..
  • 至于你的问题:select * from [login] where id = ?
  • 我是否将其添加到另一个 else if 语句中?如果是这样,我需要在 else if ( ?? ) 中添加什么

标签: c# sql-server


【解决方案1】:

假设 textBox1 是您可以使用类似这样的用户名。

cmd = new SqlCommand ("select top 1 * from Login where Username = @username", con);
cmd.Parameters.AddWithValue("@username", textBox1.Text);
bool userExists = cmd.ExecuteScalar() != null;

我强烈建议您花一些时间阅读有关参数化 SQL 查询的信息。 这是一个帮助您入门的链接https://visualstudiomagazine.com/articles/2017/07/01/parameterized-queries.aspx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-28
    • 2013-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多