【发布时间】:2021-05-12 03:53:43
【问题描述】:
我的代码有问题,我的程序使用线程从 MySQL DB 中填充 JTable,程序运行正常,但出现此错误
//错误,com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:数据源拒绝建立连接,来自服务器的消息:“连接太多” 错误 java.lang.NullPointerException//
我认为我需要关闭连接或者可能不使用线程来填充 JTable,我的想法是不使用 JButton 事件来填充表格,您对此有什么建议吗?
public class VentanaAdministrador extends javax.swing.JFrame{
public static final String URL = "jdbc:mysql://localhost:3306/floreria?autoReconnet=true&useSSL=false";
public static final String Usuario = "root";
public static final String Contraseña = "";
PreparedStatement ps;
ResultSet rs;
public Connection getConnection(){
Connection conexion = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conexion = (Connection) DriverManager.getConnection(URL,Usuario,Contraseña);
}catch(Exception ex){
System.err.println("Error, "+ex);
}
return conexion;
}
///////////////////////////////////////////////
Thread llenado = new Thread(){
public void run(){
DefaultTableModel modeloTabla = new DefaultTableModel();
TablaVentanaAsignar.setModel(modeloTabla);
PreparedStatement ps = null;
ResultSet rs = null;
try{
VentanaAdministrador con = new VentanaAdministrador();
Connection VentanaAdministrador = con.getConnection();
ps = VentanaAdministrador.prepareStatement("select NumeroEmpleado,Nombre,Punto_de_venta,TiempoTrabajo from empleados where Puesto=?");
ps.setString(1, "Diseñador");
rs = ps.executeQuery();
modeloTabla.addColumn("No. Empleado");
modeloTabla.addColumn("Nombre");
modeloTabla.addColumn("Sucursal");
modeloTabla.addColumn("Tiempo trabajado");
while(rs.next()){
Object fila[] = new Object[4];
fila[0] = rs.getObject(1);
fila[1] = rs.getObject(2);
fila[2] = rs.getObject(3);
fila[3] = rs.getObject(4);
modeloTabla.addRow(fila);
}
}catch(Exception ex){
System.err.println("Error "+ex);
}
}
};
public VentanaAdministrador() {
initComponents();
llenado.start();
}
【问题讨论】:
-
您需要在完成连接后立即关闭连接,即在您的
catch块之后,在finally块中:或者最好还是使用 try-with-resources。注意PreparedStatement和ResultSet都不应该是成员变量。 NB 2Class.forName()行自 2007 年以来就不再需要了。