0

我有一个验证的用户ID和密码,这样如何验证用户登录与WindowsForm + SqlServer的

PROCEDURE [dbo].[CheckLoginByUserIdAndPassword2]    

@UserId char(15),    
@Password char(40)   
AS          
BEGIN          
-- SET NOCOUNT ON added to prevent extra result sets from          
-- interfering with SELECT statements.          
SET NOCOUNT ON;     
    select Name, UserPersonalId, UserId from MSUSERPERSONALINFO  
    where UserId = @UserId and [email protected]   
END 

但是,任何想法的代码那种应该在我的C#(windowsform应用程序)的存储过程访问此存储过程并获得返回值,无论登录是成功还是失败?

我有我的代码调用该程序,但我仍然不能设定的返回值..

try 
      { 
       string sp_name = "dbo.CheckLoginByUserIdAndPassword2"; 

       SqlConnection SqlCon = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=jdwlrc_db;Data Source=."); 
       SqlCon.Open(); 

       SqlCommand SqlCom = new SqlCommand(sp_name, SqlCon); 

       SqlCom.CommandType = CommandType.StoredProcedure; 

       SqlCom.Parameters.Add(new SqlParameter("@UserID",nama)); 
       SqlCom.Parameters.Add(new SqlParameter("@Password",password)); 

       SqlCom.ExecuteScalar(); 
       SqlCon.Close(); 

       return true; 
      } 


      catch 
      { 
       return false; 
      } 

THX很多..

回答

0

我建议你创建一个独立的项目(一个类库)来做所有的数据库通信。这应该是我们的数据访问层。您的Windows应用程序应该是某种不直接连接到数据库的瘦客户机。然后在你的Windows项目中,添加一个对我们创建的类库的引用。添加引用后,您应该能够从您的UI项目访问类库中的函数。

当使用输入用户名和密码并单击登录按钮时,您从文本框中读取值并通过传递相关数据(在这种情况下为用户名和密码)调用类库中的函数, 。得到回应并决定下一步该做什么。

关于数据访问代码,我总是倾向于将我的代码封装在using语句中,这样我就不用担心连接是否仍然打开。

bool isValidUser=false; 
try 
{ 
string sp_name = "dbo.CheckLoginByUserIdAndPassword2"; 
using(SqlConnection SqlCon = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=jdwlrc_db;Data Source=.")) 
{ 
    SqlCommand SqlCom = new SqlCommand(sp_name, SqlCon); 
    SqlCom.CommandType = CommandType.StoredProcedure; 
    SqlCom.Parameters.AddWithValue("@UserID", nama); 
    SqlCom.Parameters.AddWithValue("@Password", password); 
    SqlCon .Open(); 
    using(SQlDataReader objReader=SqlCom.ExecuteReader()) 
    { 
     if(objReader.Read() 
     { 
     isValidUser=true; 
     //You can read the values from reader if you want for future use like storing in session etc 
     } 
    } 
    SqlCon.Close(); 
} 
} 
catch(Exception ex) 
{ 
    //Log error 
} 
+0

我会尽力让这个我的代码, 非常感谢你的解决方案可以帮助我很多:D – pegasustech 2012-04-18 09:35:04

0

你可以做这样的事情。

修改类似下面的

SELECT UserId FROM MSUSERPERSONALINFO WHERE UserId = @UserId AND [email protected] 

并在代码

object result = sqlCom.ExecuteScalar(); 
if(result != null && int.Parse(result.ToString()) > 1) 
{ 
//Authenticated successfully. 
} 
else 
{ 
//Authentication failed 
} 

希望它可以帮助你的存储过程。

+0

大赏! :D 非常感谢你,还是你们两个真的启发我如何得到这个骑:) :) 抱歉不能给你积分,因为我在这里新的.. 真的很感谢你:) – pegasustech 2012-04-19 09:16:33