2010-05-22 72 views
2

我是一个初学者编码器,我正在建立一个项目使用C#Asp.Net在其中我注册用户与用户ID,现在我的问题是,如何检查用户ID是已经存在于用户表中或者当用户试图注册时,我正在使用sql server 2000?如何检查用户标识已存在

+0

你在使用它们来访问数据库技术? – 2010-05-22 06:25:05

+0

我正在使用ado.net – Sheery 2010-05-22 06:29:30

+0

嗨,我正在使用这个,但它给出了一个错误CS0103:名称'User_id'在当前上下文中不存在。我的代码示例是这样的 con = new SqlConnection(“server = NEW-80DF4B540E3; database = Cv_Manage; uid = sa; pwd = micron”); cmd = new SqlCommand(“select * from tbl_userlogin where User_id = username。文本“,con); 如果(username.Text == User_id) { MessageBox.Show(”User Id already exists“); } – Sheery 2010-05-22 06:45:20

回答

10

根据你评论中的代码,我想说你需要的是一个关于如何使用ADO.NET查询数据的好介绍性教程,如果任何人都可以推荐的话。

首先,你不能只在你的查询中使用“username.Text”,SQL Server对你的ASP.NET页面一无所知,它是“用户名”TextBox。

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

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#代码中引用数据库中的字段,这就是你得到CS0103编译错误的原因。

SqlDataReader reader = cmd.ExecuteReader(); 

现在,您的SqlDataReader具有查询结果。既然你关心的是它是否找到了某些东西,你可以使用HasRows属性来检查它是否返回任何东西。

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

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

3

你可以简单地查询从数据库中用户:

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

如果有任何记录,这意味着,用户被引导,如果没有,你可以将其插入到表中。

+0

嗨,我使用这个,但它给错误CS0103:我的代码示例是这样的 con = new SqlConnection(“server = NEW-80DF4B540E3; database = Cv_Manage; uid = sa; pwd = micron”); cmd = new SqlCommand(“select * from tbl_userlogin where User_id = username.text“,con); if(username.Text == User_id) {MessageBox.Show(”User Id already exists“);} – Sheery 2010-05-22 06:47:48

+0

你缺少一些基础知识:你运行了查询并检查其是否正确?查询 - 从tbl_userlogin中选择*其中User_id ='username.text',并且是您的代码中声明的User_id? – 2010-05-22 07:01:49

+0

User_id i是表tbl_userlogin的数据库字段,其中username是用户输入值的文本框 – Sheery 2010-05-22 07:06:39

0

它很简单。首先尝试获取(选择)所需用户的记录。

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

如果返回任何记录其平均用户是已经存在。
如果没有记录返回,则意味着相同的用户标识不存在,并且您将此用户标识用于新用户。

相关问题