【问题标题】:java command to call a getconnection method from one class to anotherjava命令从一个类调用getconnection方法到另一个类
【发布时间】:2017-04-19 14:12:53
【问题描述】:
 public class A {


    // method to get connection
    ComboPooledDataSource cpDataSource = new ComboPooledDataSource();

    public Connection getconnection() throws Exception {

        Connection con = null;
        try {
            // open a connection
            con = cpDataSource.getConnection();

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return con;
    }


      public Class B {


        Statement stat = null;      

        Connection con = getconnection();
        stat = con.createStatement();
        stat.execute("create table if not exists Node1(id int NOT NULL AUTO_INCREMENT, name varchar(255), ip varchar(255), port int, site varchar(255), object_referenece varchar(255), connectivity_status varchar(255))");
        closeConnection(con,stat);



 public  void closeConnection(Connection con, Statement stat) throws 
 SQLException {
    stat.close();
   con.close();

 }
 }

我有这两个类,B类纯粹用于创建表。我需要从 A 类中获取 getConnection 方法才能在 B 类中继续。当我使用此语法时,它要求我在此类中再次创建 getconnection 方法。有什么方法可以从 A 类中获取方法并在 B 类中使用?

【问题讨论】:

  • 您的代码有点乱,请检查一下。类B 不见了。

标签: java database h2


【解决方案1】:

您可能需要重新考虑代码的结构。为什么您希望内部类执行一些您可以放在原始类 A 中的方法中的代码。
但是,如果出于某种原因您仍希望类 B 作为类 A 中的内部类,则需要更改语法。

public class A {

    ComboPooledDataSource cpDataSource = new ComboPooledDataSource();

    public Connection getConnection() {
        Connection con = null;
        try {
            // open a connection
            con = cpDataSource.getConnection();

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return con;
    }

    public class B {

        public void createTable() {
            Connection con = getConnection();
            try {
                Statement stmt = con.createStatement();
                stmt.execute("create table if not exists Node1(id int NOT NULL AUTO_INCREMENT, name varchar(255), ip varchar(255), port int, site varchar(255), object_referenece varchar(255), connectivity_status varchar(255))");
            } catch(SQLException ex) {
                ex.printStackTrace();
            }
            closeConnection(con, stmt);
        }

    }

}

注意public class B 的小写class,因为您不想定义java.lang.Class 类型的属性。另请注意,B 类中的代码现在包含在方法 public void createTable() 中,因为您不能只在 java 类中的任何构造函数/方法之外有代码块。
您还想将 Statement creationexecution 放在 try/catch 块中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-07
    • 1970-01-01
    • 2016-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多