为什么我不能在构造函数外执行查询?我不能使用我在构造函数中声明的变量。为什么不?我是否必须将数据库连接放在带参数的方法中?
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);
}
}
}
最佳答案
con 在您的构造函数范围内。使用
连接控制;
作为类变量并在构造函数中
con = DriverManager.getConnection("jdbc:mysql://localhost/project","root","password");
只用这个。对所需变量执行相同操作。您需要在整个类(class)中使用它。
关于java - 我不能在构造函数之外使用数据库连接,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13824640/