如何为多个请求实例化 1 个连接 class?
How to instance 1 connection class for multiple requests?
所以我目前正在做一个将使用数据库的项目,但这是我第一次尝试在 java 上摆弄它。
但是我已经看到我的第一个问题是我如何制作一个处理连接的文件,而其他文件处理 GET/ADD/UPDATE/DELETE(每个 table 一个)什么才是最好的方法?
不必在每个文件中放置连接值并执行连接
我想扩展与其他 class 的连接 class,但我不知道这是个好主意。
import java.sql.*;
public class DatabaseConnection {
public static void main(String[] args) {
final String url = "jdbc:postgresql://localhost:5432/Database";
final String user = "dbuser";
final String password = "dbpass";
try(Connection conn = DriverManager.getConnection(url, user, password)) {
System.out.println("Connection successful!");
} catch (SQLException e) {
System.out.println("Connection failure.");
e.printStackTrace();
}
}
}
最好的方法是什么?
也许我错了,但我认为您需要连接池。
尝试在此处查找说明 https://www.baeldung.com/java-connection-pooling
您可以将与数据库连接相关的代码移动到实用程序 class,并使用 PreparedStatement
class 预编译 SQL 查询
public class doSomething {
Connection conn = null;
PreparedStatement pst = null;
public static void main(String [] args){
conn = DatabaseConnection.connect()
String qry = "Select * from table_name";
pst = (PreparedStatement) conn.prepareStatement(qry);
}
}
所以我目前正在做一个将使用数据库的项目,但这是我第一次尝试在 java 上摆弄它。 但是我已经看到我的第一个问题是我如何制作一个处理连接的文件,而其他文件处理 GET/ADD/UPDATE/DELETE(每个 table 一个)什么才是最好的方法? 不必在每个文件中放置连接值并执行连接
我想扩展与其他 class 的连接 class,但我不知道这是个好主意。
import java.sql.*;
public class DatabaseConnection {
public static void main(String[] args) {
final String url = "jdbc:postgresql://localhost:5432/Database";
final String user = "dbuser";
final String password = "dbpass";
try(Connection conn = DriverManager.getConnection(url, user, password)) {
System.out.println("Connection successful!");
} catch (SQLException e) {
System.out.println("Connection failure.");
e.printStackTrace();
}
}
}
最好的方法是什么?
也许我错了,但我认为您需要连接池。 尝试在此处查找说明 https://www.baeldung.com/java-connection-pooling
您可以将与数据库连接相关的代码移动到实用程序 class,并使用 PreparedStatement
class 预编译 SQL 查询
public class doSomething {
Connection conn = null;
PreparedStatement pst = null;
public static void main(String [] args){
conn = DatabaseConnection.connect()
String qry = "Select * from table_name";
pst = (PreparedStatement) conn.prepareStatement(qry);
}
}