开发者

How to check user id already exists

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?


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.

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.

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);

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();

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");
    }

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.


You can simply query for the user from the database:

select * from User where user_id=<new-input-id>

If there is any record, that means the user is taken and if not, you can insert it into the table.


As you are a beginner know the basic concepts in Ado.net it would help you better

http://msdn.microsoft.com/en-us/library/e80y5yhx%28VS.80%29.aspx

http://www.csharphelp.com/2007/06/using-ado-net-database-1-for-beginners/

http://www.codeproject.com/kb/database/databaseacesswithadonet1.aspx


Its so simple. first you try to get(select) the record of desired user.

`Select * from UserTable where userId = <your-input-userid>`

If it returns any record its mean that the user is already exist.
If no record returns , Its mean that the same userid is not already exist and you use this user id for new user.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜