[英]Determining if user login already exists in database?
I am building a web application in asp.net using C#. 我正在使用C#在asp.net中构建Web应用程序。 I have the Form where the user should register and then can login.
我有用户应在其中注册然后可以登录的表格。 I am having a problem in making the web app know that the name which the user picks is either "already exists" or not.
我在使Web应用程序知道用户选择的名称是否“已经存在”时遇到问题。 If it already exists it should not insert the same name and display a message saying "user name already exists".
如果已经存在,则不应插入相同的名称,并显示一条消息,指出“用户名已存在”。 I have tried the
SqlDataReader
but no luck. 我尝试了
SqlDataReader
但是没有运气。
protected void Register_Button_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BJ_Player_String"].ToString());
SqlCommand cmd = new SqlCommand();
SqlCommand cmd2 = new SqlCommand();
SqlDataReader data_reader;
String name = TextBox2.Text;
String date = TextBox3.Text;
try
{
conn.Open();
cmd = new SqlCommand("Insert into BJ_Player (Player_Name, D_O_B) Values (@Player_name, @D_O_B)", conn);
cmd = new SqlCommand("Select Player_Name from BJ_Player WHERE Player_Name = @Player_name", conn);
cmd.Parameters.Add("@Player_name", SqlDbType.NVarChar).Value = name;
cmd.Parameters.Add("@D_O_B", SqlDbType.Date).Value = date;
cmd.Connection = conn;
data_reader = cmd.ExecuteReader();
cmd.ExecuteNonQuery();
if (data_reader.HasRows)
{
lblPlayerNameExists.Visible = true;
}
else
{
// do nothing
}
}
Make Player_Name unique in database then it will give you exception when you try to insert. 使Player_Name在数据库中唯一,然后在尝试插入时会给您异常。 You have to use unique constraint.
您必须使用唯一约束。 You have to give command type also and check you assigned both queries to same cmd object
您还必须提供命令类型,并检查是否将两个查询都分配给同一cmd对象
in your code you're inserting data in your DB and then you are examining that the name is the same or not. 在代码中,您要在数据库中插入数据,然后检查名称是否相同。 first you should search the name in your DB and then if there isn't any record with that name ,you should add your record.
首先,您应该在数据库中搜索名称,然后如果没有任何使用该名称的记录,则应添加记录。
If you would like to write a model function to do that then 如果您想编写一个模型函数来执行此操作
I usually do it in one of two ways: 我通常以以下两种方式之一进行操作:
Using the merge statement may help with this. 使用merge语句可能对此有所帮助。 Merge performs insert, update, or delete operations on a target table based on the results of a join with a source table.
合并根据与源表的联接结果在目标表上执行插入,更新或删除操作。
Basically it inserts when needed, and updates when needed. 基本上,它在需要时插入,并在需要时更新。 Often times referred to as an upsert.
通常被称为upsert。 but it gets the job done.
但它完成了工作。
Here is a link to a site explaining how to use merge. 这是指向网站的链接,解释了如何使用合并。 Looks like a good article.
看起来不错。 http://www.kodyaz.com/articles/sql-server-2008-t-sql-merge-statement-example.aspx
http://www.kodyaz.com/articles/sql-server-2008-t-sql-merge-statement-example.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.