我的netbeans桌面应用程序中有一个jtable,我想从数据库中填充它。
我想知道绑定代码以及在插入/删除某些条目后如何刷新表。
我有一个按钮,显示包含jtable的框架,action命令在
之下 try{
Class.forName("Mydrivername").newInstance();
Connection con=DriverManager.getConnection(connectionurl,id,password);
PreparedStatement ps=(PreparedStatement) con.preparedStatement("select * from datavasetablename");
ResultSet rs= ps.executeQuery();
while(rs.next()){
row[0]= rs.getInt("Id");
row[1]= rs.getString("name");
mytablemodel.addRow(row);
frame.show();
}
} catch(Exception e){
}
当我第一次显示框架时,一切都很好但是当我隐藏框架并再次显示时,一切都完全消失了。
答案 0 :(得分:0)
在每次插入删除中,我都用
重新加载public Object[][] getDatos() {
int registros = 0;
//We first perform the COUNT to know the size of the matrix
try {
PreparedStatement pstm = con.getConnection().prepareStatement(""
+ "SELECT count(idDocente) as total FROM docente;");
ResultSet res = pstm.executeQuery();
res.next();//registros es igual al numero de materiales en la BD
registros = res.getInt("total");
res.close();
} catch (SQLException e) {
System.out.println(e);
}
//declaramos el tamaño de la matriz[numero de materiales][cantidad de atributos]
Object[][] fila = new String[registros][6];
try {
PreparedStatement pstm = con.getConnection().prepareStatement("SELECT "
+ " codigo,nombre,apaterno,amaterno,telefono,correoElectronico "
+ " FROM docente"
+ " ORDER BY idDocente;");
ResultSet res = pstm.executeQuery();
int i = 0;
while (res.next()) {
String estCodigo = res.getString("codigo");
String estNombre = res.getString("nombre");
String estCantidad = res.getString("apaterno");
String estDescripcion = res.getString("amaterno");
String estFecha = res.getString("telefono");
String estISBN = res.getString("correoElectronico");
fila[i][0] = estCodigo;
fila[i][1] = estNombre;
fila[i][2] = estCantidad;
fila[i][3] = estDescripcion;
fila[i][4] = estFecha;
fila[i][5] = estISBN;
i++;
}
res.close();
} catch (SQLException e) {
e.printStackTrace();
}
return fila;
}
查看:
private void updateTabla() {
String[] columNames = {"Code:", "Name:", "Surname:", "Surname", "Cell phone:", "E-mail:"};
dtMaterial = objCtrl.getDatos();
DefaultTableModel datos = new DefaultTableModel(dtMaterial, columNames);
tblMaterial.setModel(datos);
}
答案 1 :(得分:0)
据我所知,实例化row
对象的代码应该也放在while(rs.next()){
语句中,然后才能正常工作。
如果您使用相同的实例,则列表中的所有项目将具有相同的属性。例如:
try{
Class.forName("Mydrivername").newInstance();
Connection con=DriverManager.getConnection(connectionurl,id,password);
PreparedStatement ps=(PreparedStatement) con.preparedStatement("select * from datavasetablename");
ResultSet rs= ps.executeQuery();
while(rs.next())
{
row = new YourRowType();// Change this line to the correct type of the row object
row[0]= rs.getInt("Id");
row[1]= rs.getString("name");
mytablemodel.addRow(row);
frame.show();
}
}
catch(Exception e)
{
}