Java 如何在类之间共享数据库连接?(JDBC)
我试图找出如何在类之间共享与数据库的已建立连接,以执行不同的SQL语句。 我通读了一些主题,但由于我对编程相当陌生,我很难将给定的信息适应我的问题 问题:我有两个类,一个打开到数据库的连接,执行一些SQL语句,调用另一个类只使用不同的表和SQL语句执行相同的操作。 现在,只要我使用自己的主方法和连接分别运行这些类,一切都很好。但是,当一个类调用另一个类时,我会得到不同的异常,这取决于我迄今为止尝试的解决方法(要么MySQLNonTransientConnectionException:Data source拒绝建立连接,要么StackOverflowException) 下面是我如何尝试建立一个用于在两个不同类中执行某些sql操作的连接:Java 如何在类之间共享数据库连接?(JDBC),java,mysql,jdbc,Java,Mysql,Jdbc,我试图找出如何在类之间共享与数据库的已建立连接,以执行不同的SQL语句。 我通读了一些主题,但由于我对编程相当陌生,我很难将给定的信息适应我的问题 问题:我有两个类,一个打开到数据库的连接,执行一些SQL语句,调用另一个类只使用不同的表和SQL语句执行相同的操作。 现在,只要我使用自己的主方法和连接分别运行这些类,一切都很好。但是,当一个类调用另一个类时,我会得到不同的异常,这取决于我迄今为止尝试的解决方法(要么MySQLNonTransientConnectionException:Data
public ClassA{
public static Connection dbConn;
//Set up a connection to the database
String dbURL = "jdbc:mysql://<some database>"; //put host, port and database here
Properties connectionProbs = new Properties();
connectionProbs.put("user", "root"); //insert USER here
connectionProbs.put("password", "root"); //insert PASSWORD here
dbConn = null;
try{
dbConn = DriverManager.getConnection(dbURL, connectionProbs);
PreparedStatement useStmt;
try{
useStmt = dbConn.prepareStatement("USE <some database>"); //insert DATABASE here
useStmt.executeUpdate();
}
catch(SQLException e){
e.printStackTrace();
}
//Do some SQL operations
//Call class B to do some SQL operations using the same connection
}
catch(SQLException e){
System.err.println("There was a problem connecting to the database");
e.printStackTrace();
}
finally{
if(dbConn != null)
try{dbConn.close();}catch(SQLException e){e.printStackTrace();}
}
}
另一方面,如果我试图建立两个单独的连接(使用与上面相同的代码)到同一个数据库(同时运行),我会得到MySQLNonTransientConnectionException:数据源拒绝建立连接
最好的处理方法是什么?我在论坛中偶然发现了ConnectionPool,但我找不到一个初学者友好的来源来详细说明如何将其付诸实践。是否有一种直接的方法来确保不同的类可以在一个数据库上连接和操作
感谢您的反馈我会避免将连接放在静态变量中。在你的特殊情况下,这并不会造成很大的差异,但最好不要养成这样做的习惯
您应该创建一个控制类来创建数据库连接,然后将其作为方法参数传递给其他两个类。通过这种方式,控制类可以处理其他类引发的任何异常,并确保连接正确关闭。您可以通过为类a中的连接创建一个非静态全局变量,然后创建一个非静态公共方法来返回此连接,如下所示
public ClassA{
// non-static global private Connection object
private Connection dbConn = null;
// non-static public method to get dbConn connection object
public Connection getConnection() {
// this condition will check if the Connection is not already open then open it.
if(null == dbConn) {
//Set up a connection to the database
String dbURL = "jdbc:mysql://<some database>"; //put host, port and database here
Properties connectionProbs = new Properties();
connectionProbs.put("user", "root"); //insert USER here
connectionProbs.put("password", "root"); //insert PASSWORD here
try{
dbConn = DriverManager.getConnection(dbURL, connectionProbs);
PreparedStatement useStmt;
try{
useStmt = dbConn.prepareStatement("USE <some database>"); //insert DATABASE here
useStmt.executeUpdate();
}
catch(SQLException e){
e.printStackTrace();
}
//Do some SQL operations
//Call class B to do some SQL operations using the same connection
}
catch(SQLException e){
System.err.println("There was a problem connecting to the database");
e.printStackTrace();
}
finally{
if(dbConn != null)
try{dbConn.close();}catch(SQLException e){e.printStackTrace();}
}
}
return dbConn;
}
}
希望这对你有所帮助
您应该创建一个控制类来创建数据库连接,然后将其作为方法参数传递给其他两个类
您能发布编译并显示您的问题的代码吗?您给了我们一个没有方法、构造函数或状态的类,其中只包含一些应该是某种方法的代码。请给我们真实的代码。你是对的。我没有发布实际的代码,因为它超过600行。我不想用不必要的数据向您发送垃圾邮件,但我意识到所选择的代码片段远不是完美的(我对编码一无所知)。我发现stackOVerflow与完全不同的东西有关。我想你们会马上找到的。谢谢你的建议。如上所述,我对编程一无所知。我可以问一下(一个来源),一个人如何通过一个连接而不把它弄得乱七八糟,或者要注意什么陷阱吗?谢谢Shishir。我将尝试在我的程序中实现这一点。我是否应该像上面提到的Mark那样将getConnection()方法放入一个单独的类中?您可以在同一个类中拥有
getConnection()
方法。
public ClassA{
// non-static global private Connection object
private Connection dbConn = null;
// non-static public method to get dbConn connection object
public Connection getConnection() {
// this condition will check if the Connection is not already open then open it.
if(null == dbConn) {
//Set up a connection to the database
String dbURL = "jdbc:mysql://<some database>"; //put host, port and database here
Properties connectionProbs = new Properties();
connectionProbs.put("user", "root"); //insert USER here
connectionProbs.put("password", "root"); //insert PASSWORD here
try{
dbConn = DriverManager.getConnection(dbURL, connectionProbs);
PreparedStatement useStmt;
try{
useStmt = dbConn.prepareStatement("USE <some database>"); //insert DATABASE here
useStmt.executeUpdate();
}
catch(SQLException e){
e.printStackTrace();
}
//Do some SQL operations
//Call class B to do some SQL operations using the same connection
}
catch(SQLException e){
System.err.println("There was a problem connecting to the database");
e.printStackTrace();
}
finally{
if(dbConn != null)
try{dbConn.close();}catch(SQLException e){e.printStackTrace();}
}
}
return dbConn;
}
}
A a = new A();
PreparedStatement Stmt = a.getConnection().prepareStatement("INSERT INTO table(ID, name) VALUES (?,?)");
public class ConnectionManager {
private static String url = "jdbc:mysql://localhost:3306/DbName";
private static String username = "YourUsername";
private static String password = "yourDbPass";
private static Connection con;
public static Connection getConnection() throws Exception {
con = DriverManager.getConnection(url, username, password);
return con;
}
}
public class main {
public static void main(String[] args) throws Exception {
Connection con = null;
con = ConnectionManager.getConnection();
CrudCity s = new CrudCity();
s = s.read(con);
System.out.println(s);
CrudCountry c = new CrudCountry();
c = c.read(con);
System.out.println(c);
CrudCountryLanguage lang = new CrudCountryLanguage();
lang = lang.read(con);
System.out.println(lang);
}
}
public class CrudCity extends City implements CrudInterface {
public CrudCity read(Connection con) throws Exception{
CrudCity p = new CrudCity();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT ID,Name,CountryCode FROM world.city");
while (rs.next()) {
p.setId(rs.getInt("ID"));
p.setName(rs.getString("Name"));
p.setCountryCode(rs.getString("CountryCode"));
}
rs.close();
return p;
}
}
public class CrudCountry extends Country implements CrudInterface{
public CrudCountry read(Connection con) throws Exception{
CrudCountry c = new CrudCountry();
Statement stmt =con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT Code,Name,Continent FROM world.country");
while (rs.next()) {
c.setCountryCode(rs.getString("Code"));
c.setCountryName(rs.getString("Name"));
c.setCodeContinent(rs.getString("Continent"));
}
rs.close();
return c;
}
}