【问题标题】:I can't use the database connection outside the constructor, why?我不能在构造函数之外使用数据库连接,为什么?
【发布时间】:2012-11-29 06:21:12
【问题描述】:

为什么我不能在构造函数之外执行查询?我不能使用我在构造函数中声明的变量。为什么不?我必须将数据库连接放在带参数的方法中吗?

public class main extends javax.swing.JFrame
{
    DefaultListModel model = new DefaultListModel();

    public main()
    {
        initComponents();
        try
        {
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost/project", "root", "password");
            Statement stat = con.createStatement();
            ResultSet resultaat = stat.executeQuery(query);

            while (resultaat.next())
            {
                model.addElement(resultaat.getString(2));
            }
        }
        catch (Exception ex)
        {
            System.out.println(ex);
        }
    }
}

【问题讨论】:

    标签: java mysql netbeans


    【解决方案1】:

    con 在你的构造函数范围内。使用

    Connection con;

    作为类变量并在构造函数中

    con = DriverManager.getConnection("jdbc:mysql://localhost/project","root","password");
    

    只使用这个。对所需变量执行相同操作。您需要在整个课程中使用它。

    【讨论】:

      【解决方案2】:

      我不能使用我在构造函数中声明的变量。为什么不呢?

      因为,由于它们是在构造函数中声明的,所以它们仅限于该范围。您无法在构造函数之外访问它们。如果您想在构造函数之外使用它们,请将它们作为实例变量,您应该首先这样做。

      你的班级应该是这样的:

      public class DBConnection {
        Connection con=null;
        public DBConnection() {
          initComponents();
          try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost/project","root","password");
          }
          catch(SQLException ex) {
          }
        }
      
        public void doDBOps() {
          String yourQuey="whatever";
          PreparedStatement stmnt = this.conn.preparedStatement(yourQuery);
          ResultSet rs = stmnt.executeQuery();
          //rest of your code 
        }
      }
      

      【讨论】:

        【解决方案3】:

        在方法或构造函数中定义的变量仅限于该范围。如果你想初始化一个变量并在你的类中使用它,你必须把它变成一个类字段(因此,将它的范围扩大到类本身),按照惯例,定义一个 get 和/或 @987654322 @方法。

        【讨论】:

          【解决方案4】:

          看来您总体上正在寻找的是数据库的单例类。您可以在其他类中使用该类来访问现有的连接,而不是每次都使用DriverManager 工厂来获取新的连接对象。

          下面的样本是从here无耻盗用的

          public class DBConnectionSingleton
          {
            private static DBConnectionSingleton instance = null;
            private static Connection conn;
            private DBConnectionSingleton()
            {
              String dbDriver = ..
              String url = ..
              String username= ..
              String password = ..
              try
              {
                Class.forName(dbDriver);
                conn = DriverManager.getConnection(url, username, password);
              }
              catch (ClassNotFoundException cnfErr)
              {
                cnfErr.printStackTrace();
              }
              catch (SQLException err)
              {
                err.printStackTrace();
              }
            }
          
            public static DBConnectionSingleton getInstance()
            {
              if (instance == null)
                return new DBConnectionSingleton();
              else
                return instance;
            }
            public static Connection getConnection()
            {
              return conn;
            }
          }
          

          【讨论】:

          • 看起来这个例子中的单例instance 从未被初始化...?
          猜你喜欢
          • 1970-01-01
          • 2020-03-06
          • 2011-11-05
          • 2015-06-14
          • 2016-02-17
          • 2013-08-16
          • 1970-01-01
          • 2017-06-04
          • 2022-12-11
          相关资源
          最近更新 更多