gpt4 book ai didi

java - 使用 JDBC 调用 sql server 存储过程时出现 java.lang.NullPointerException

转载 作者:行者123 更新时间:2023-12-01 10:36:05 25 4
gpt4 key购买 nike

我试图通过 JDBC 调用数据库来获取存储过程数据。当我执行下面的代码时,我得到 resultet=null,我的代码有什么错误?请指导我。

存储过程

CREATE PROCEDURE getEmpDetails
AS
BEGIN
SELECT * FROM Employees;
END

java文件

 // JDBC driver name and database URL
static final String JDBC_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
static final String DB_URL = "jdbc:sqlserver://localhost;database=JDBCDatabase";

// Database credentials
static final String USER = "hj";
static final String PASS = "kalpana";

public static void main(String[] args) {
Connection con = null;
ResultSet rs = null;
CallableStatement stmt = null;

try{
//STEP 2: Register JDBC driver
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

//STEP 3: Open a connection
System.out.println("Connecting to database...");
con = DriverManager.getConnection(DB_URL,USER,PASS);

//STEP 4: Execute a query
System.out.println("Creating statement...");
// stmt = conn.createStatement();

stmt = con.prepareCall("{call getEmpDetails}");

ResultSet resultSet = stmt.getResultSet();

System.out.println("resultset"+resultSet);

if (resultSet.next()) {
// Then we use a loop to retrieve rows and column data
// and creates a html coded table output
System.out.println("<table border='1' >");
do {
System.out.println("<tr>");
System.out.print("<td>" + resultSet.getString("id") + "</td>");
System.out.print("<td>" + resultSet.getString("first") + "</td>");
System.out.println("<td>" + resultSet.getInt("last") + "</td>");
System.out.println("<td>" + resultSet.getDouble("age") + "</td>");
System.out.println("</tr>");
} while (resultSet.next());
System.out.println("</table>");
}
}catch(Exception e){
e.printStackTrace();
}finally{
try {
stmt.close();
con.close();
// input.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

}
}

最佳答案

在代码中,您准备调用,然后预期结果 - 但不执行查询。尝试将 ResultSet 上的访问器更改为查询的实际执行:

   stmt = con.prepareCall("{call getEmpDetails}"); 
//Do it!
ResultSet resultSet = stmt.executeQuery();

关于java - 使用 JDBC 调用 sql server 存储过程时出现 java.lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34715527/

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