gpt4 book ai didi

java - SQL Server 存储过程和 jdbc

转载 作者:行者123 更新时间:2023-11-30 04:32:27 25 4
gpt4 key购买 nike

我正在努力使用 SQL Server 2005 和 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 查询。

最佳答案

尝试以下操作:

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

此外,我建议仅选择计数(select count(*) as cnt from ...),并使用类似 int count = rs.next() 的方法。 getInt("cnt");

关于java - SQL Server 存储过程和 jdbc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14332980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com