gpt4 book ai didi

java - 没有关闭就返回结果集?

转载 作者:搜寻专家 更新时间:2023-10-30 23:47:25 27 4
gpt4 key购买 nike

我想要一个数据库连接管理类,我可以使用它来执行简单的 SQL 命令,例如 SELECTINSERT 等。调用这样的东西(下面的类):

ResultSet test = DataService.getResultSet("SELECT NOW()");
test.first();
System.out.println(test.getString(1));

这是我在网上找到的类(class):

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
* Database object to load drivers and perform queries
* @author Abdulsalam Umar blog.salamtura.com
*/
public class DataService {

private static Connection con;
private static final String Driver = "oracle.jdbc.driver.OracleDriver";
private static final String ConnectionString = "Your database connection string";
private static final String user = "username";
private static final String pwd = "password";

/**
* create Database object
*/
public DataService() {
}

/**
* to load the database base driver
* @return a database connection
* @throws SQLException throws an exception if an error occurs
*/
public static Connection loadDriver() throws SQLException {
try {
Class.forName(Driver);
} catch (ClassNotFoundException ex) {
System.out.println(ex.getMessage());
}
con = DriverManager.getConnection(ConnectionString, user, pwd);
return con;
}

/**
* to get a result set of a query
* @param query custom query
* @return a result set of custom query
* @throws SQLException throws an exception if an error occurs
*/
public static ResultSet getResultSet(String query) throws SQLException {
Connection con = loadDriver();
ResultSet rs;
PreparedStatement st = con.prepareStatement(query);
rs = st.executeQuery();

return rs;
}

/**
* to run an update query such as update, delete
* @param query custom query
* @throws SQLException throws an exception if an error occurs
*/
public static void runQuery(String query) throws SQLException {
Connection con = loadDriver();
ResultSet rs;
PreparedStatement st = con.prepareStatement(query);
st.executeUpdate();
}
}

这种返回 ResultSet 而不关闭它(并关闭语句)的方式对吗?如何从方法中返回 ResultSet

最佳答案

返回结果集不是一个好主意。因此,获取所需的数据并利用集合返回数据。 This answer may be useful

关于java - 没有关闭就返回结果集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26700304/

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