2013-01-15 59 views
1

我正在努力与SQL Server 2005和JDBC。我有一个存储过程:SQL Server存储过程和jdbc

set ANSI_NULLS ON 
set QUOTED_IDENTIFIER ON 
go 

ALTER proc [dbo].[sp_logincheck] 
    @username as nvarchar(50), 
    @password as nvarchar(50) 
as 
begin 
    select * 
    from users 
    where user_name = @username 
     and password = @password 
     and is_active = 'Yes' 
end 

而且我User类:

import java.sql.*; 

public class User { 
    private String username; 

    private User(String username){ 
     this.username = username; 
    } 

    public static User login(String username, char [] password) throws SQLException{ 
     if(username == null || password == null){ 
      throw new IllegalArgumentException("Illegal arguments passed to method"); 
     } 
     if(login1(username, password)){ 
      return new User(username); 
     } 
     return null; 
    } 

    private static boolean login1(String username, char [] password) throws SQLException{ 
     Connection connection = null; 
     CallableStatement statement = null; 
     try{ 
      connection = DriverManager.getConnection(AppParameters.dbURL, AppParameters.dbUsername, AppParameters.dbPassword); 
     }catch(SQLException e){ 
      throw e; 
     } 
     try{ 
      statement = connection.prepareCall("{ ? = call dbo.sp_logincheck(?,?) }"); 
      statement.registerOutParameter(1, Types.INTEGER); 
      statement.setString(2, username); 
      statement.setString(3, new String(password)); 
      statement.execute(); 
      if(statement.getInt(1) == 1){ 
       System.out.println("Login Successfull"); 
       return true; 
      } 
      System.out.println("Login Failed"); 
      return false; 
     }catch(SQLException sqle){ 
      sqle.printStackTrace(); 
      throw sqle; 
     }finally{ 
      try{ 
       statement.close(); 
      }catch(Exception e){ 
      } 
      try{ 
       connection.close(); 
      }catch(Exception e){ 
      } 
     } 
    } 

    public String getUsername(){ 
     return username; 
    } 
} 

调用login()方法始终打印Login Failed。如何在SQL Server中使用存储过程并使用JDBC执行用户登录?或者用原始SQL语句更好?请在此引导我。

编辑:

我也想知道如何从上面的存储过程的ResultSet,因为我有这个存储过程里面select查询。

回答

1

尝试以下操作:

ResultSet rs = statement.executeQuery(); 
if (! rs.isLast()) { 
    // match 
} else { 
    // no match 
} 

另外,我建议只选择计数(select count(*) as cnt from ...),并使用像int count = rs.next().getInt("cnt");

+0

它的工作..但不是使用if(!rs.isLast()),我使用返回rs.next();它会没事的,对吧? – UDPLover

+0

@Meraman是的,这也适用。 – gaborsch

1

尝试将存储过程中的sql语句中的select * from users...更改为select count(*) from users...

否则你的表情if(statement.getInt(1) == 1){没有意义。

+0

我这样做,但相同的输出:( – UDPLover

+0

在改变存储过程之后,你是否重新启动了应用程序? – Andremoniy

+0

是的,我做过了,但它不工作:( – UDPLover

0

如果

statement.getInt(1)
等于产生的行数或至少有一行。那么这可能是数据不匹配的情况。没有找到数据

+0

从声明中读取没有意义,他可以得到他设置的查询的第一个参数的值,它如果是int。你甚至可以在调用查询之前做到这一点,这肯定不会包含任何结果。 – gaborsch