【发布时间】:2021-12-15 22:28:00
【问题描述】:
如何检查给定的用户名是否存在于数据库中?
我需要程序在用户按下注册按钮时显示用户名是否存在,因为目前如果我输入一个现有的用户名,我的程序会出错并崩溃。
我的表名为Login,插入表有Username和Password。
代码:
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