如何检查用户ID已经存在 [英] How to check user id already exists

查看:429
本文介绍了如何检查用户ID已经存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是初学者codeR,我建立使用C#Asp.Net中对此我注册用户提供一个用户ID的一个项目,现在我的问题是,如何检查该用户ID已经存在于用户表或没有时,用户尝试注册,我使用SQL Server 2000?

I am a beginner coder, i am building a project using C# Asp.Net in which i am registering users with a user id, now my question is that how to check that the user id is already exists in the user table or not when user trying to register, i am using sql server 2000?

推荐答案

根据您的评论的code,我说你需要的是有关如何使用ADO.NET的数据来查询一个很好的入门教程,如果任何人都可以推荐一个。

Based on the code in your comment, I'd say what you need is a good introductory tutorial on how to query data using ADO.NET, if anyone can recommend one.

首先,你不能只是在查询中使用username.Text时,SQL Server一无所知ASP.NET页面和它的用户名文本框。

First of all, you can't just use "username.Text" in your query, the SQL Server knows nothing about your ASP.NET page and it's "username" TextBox.

您需要一个参数传递到您的SqlCommand(不要的曾经的建立就像一个字符串+ username.Text,谷歌的SQL注入攻击,如果,从那里tbl_userlogin USER_ID =选择*你想知道为什么),是这样的:

You need to pass a parameter into your SqlCommand (don't ever build a string like "select * from tbl_userlogin where User_id=" + username.Text, google for "sql injection attack" if you want to know why), like this:

    SqlCommand cmd = new SqlCommand("select * from tbl_userlogin where User_id = @UserID", con);
    SqlParameter param = new SqlParameter();
    param.ParameterName = "@UserID";
    param.Value = username.Text;
    cmd.Parameters.Add(param);

然后,你需要实际执行命令,并得到一个SqlDataReader的从回来。你不能只是指从你的C#code数据库领域,这就是为什么你得到CS0103编译错误。

Then, you need to actually execute the command and get an SqlDataReader back from it. You can't just refer to fields from the database in your C# code, that's why you're getting the CS0103 compile error.

    SqlDataReader reader = cmd.ExecuteReader();

现在,您的SqlDataReader的具有从查询的结果。因为所有你关心的是它是否找到的东西,你可以使用HasRows属性检查它是否返回任何东西。

Now, your SqlDataReader has the results from the query. Since all you care about is whether or not it found something, you can use the HasRows property to check if it returned anything.

    if (reader.HasRows)
    {
        MessageBox.Show("User Id already exists");
    }

阅读上SqlDataReader对象 - <一个href=\"http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx\">http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx - 学习如何实际访问的结果,如果你需要

Read up on SqlDataReader - http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx - to learn how to actually access the results if you need to.

这篇关于如何检查用户ID已经存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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