C#sql如何防止插入多个用户名 [英] C# sql how do i prevent multiple usernames being inserted

查看:78
本文介绍了C#sql如何防止插入多个用户名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Windows窗体应用程序中有一个用于管理员用户的表单,以便他们可以添加,编辑和删除用户。我遇到的问题是管理员可以插入一个新用户,该用户与另一个用户具有相同的用户名,导致两个用户在登录系统时都有重复的用户名。



如何在数据库中创建新帐户时阻止管理员插入已经使用的用户名。





I have a form in my windows form application that is for admin users so that they can add,edit and delete users. The problem i have is that admin can insert a new user which has the same username as another user which results in both users having duplicate usernames when logging into the system.

how can i prevent admin from inserting an already taken username when creating new accounts in the database.


SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|Data.mdf;Integrated Security=True");
                con.Open();
                SqlDataAdapter sda = new SqlDataAdapter("INSERT INTO Login (FirstName,Role,Username,Password,Surname) VALUES ('" + txtfirstname2.Text + "','" + rolecombo.Text + "','" + txtusername2.Text + "','" + txtpassword2.Text + "','" + txtsurname.Text + "')", con);
                sda.SelectCommand.ExecuteNonQuery();
                con.Close();
                MessageBox.Show("SAVED SUCCESSFULLY !!!!!");





我的尝试:



我有查看了许多文章,建议在用户名中添加一个标识以使其唯一,因为我已经在表中有一个具有标识的ID列,我无法使用该解决方案因此我需要一个更简单的解决方案,例如系统抛出一个messagebox如果用户名是重复但我不知道该怎么做。



What I have tried:

I have looked across many articles which suggested adding an identity to usernames to make them unique, since i already have an ID column in the table which has an identity, i can not use the solution so therefore I need a simpler solution such as the system throwing a messagebox if username is duplicate but i'm not sure how to do that.

推荐答案

您可以将列定义为唯一,而不将它们作为标识列。尽管如此,我还会检查用户名是否已经存在而不是等待数据库代码抛出异常。



除此之外:不要错过使用字符串连接来构建SQL语句。您的代码容易受到SQL注入的影响!请改用SQL-Parameters。
You can define columns as unique without them being an identity column. Nonetheless I would check whether a username already exists and not wait for the database code to throw an exception.

Apart from that: DON'T EVER use string-concatenation to build SQL-statements. Your code becomes susceptible to SQL-injection! Use SQL-Parameters instead.


这篇关于C#sql如何防止插入多个用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆