Busqué en Google todo el día y no tuve suerte. Llamo getnPrintAllData() método getnPrintAllData() después de presionar el botón OK. Entonces el código es:
public class DatabaseSQLiteConnection { Connection conn = null; PreparedStatement statement = null; ResultSet res = null; public DatabaseSQLiteConnection(){ try{ Class.forName("org.sqlite.JDBC"); conn = DriverManager.getConnection("jdbc:sqlite:test.sqlite"); statement = conn.prepareStatement("SELECT * from product_info;"); } catch(Exception e){ e.printStackTrace(); } } public void getnPrintAllData(){ String name, supplier, id; DefaultTableModel dtm = new DefaultTableModel(); Window gui = new Window(); //My JPanel class try{ res = statement.executeQuery(); testResultSet(res); ResultSetMetaData meta = res.getMetaData(); int numberOfColumns = meta.getColumnCount(); while (res.next()) { Object [] rowData = new Object[numberOfColumns]; for (int i = 0; i < rowData.length; ++i) { rowData[i] = res.getObject(i+1); } dtm.addRow(rowData); } gui.jTable1.setModel(dtm); dtm.fireTableDataChanged(); ////////////////////////// } catch(Exception e){ System.err.println(e); e.printStackTrace(); } finally{ try{ res.close(); statement.close(); conn.close(); } catch(Exception e){ e.printStackTrace(); } } } public void testResultSet(ResultSet res){ try{ while(res.next()){ System.out.println("Product ID: "+ res.getInt("product_id")); System.out.println("Product name: "+ res.getString("product_name")); System.out.println("Supplier: "+ res.getString("supplier")); } } catch(Exception e){ e.printStackTrace(); } } }
Mi método testResultSet() funciona correctamente. Ahora, ¿cómo cambiar mi código para que funcione, o cuál es el código más simple para hacer DefaultTableModel de ResultSet ? Gracias por adelantado.
Editar: estoy recibiendo java.lang.IllegalStateException: SQLite JDBC: inconsistent internal state error de java.lang.IllegalStateException: SQLite JDBC: inconsistent internal state .
Creo que la forma más sencilla de construir un modelo a partir de una instancia de ResultSet podría ser la siguiente.
public static void main(String[] args) throws Exception { // The Connection is obtained ResultSet rs = stmt.executeQuery("select * from product_info"); // It creates and displays the table JTable table = new JTable(buildTableModel(rs)); // Closes the Connection JOptionPane.showMessageDialog(null, new JScrollPane(table)); }
El método buildTableModel :
public static DefaultTableModel buildTableModel(ResultSet rs) throws SQLException { ResultSetMetaData metaData = rs.getMetaData(); // names of columns Vector columnNames = new Vector(); int columnCount = metaData.getColumnCount(); for (int column = 1; column <= columnCount; column++) { columnNames.add(metaData.getColumnName(column)); } // data of the table Vector> data = new Vector>(); while (rs.next()) { Vector
Creo que esta es la manera más fácil de poblar / modelar una tabla con ResultSet .. Descargar e incluir rs2xml.jar Obtenga rs2xml.jar en sus bibliotecas …
Bueno, estoy seguro de que esta es la forma más simple de poblar JTable de ResultSet, sin ninguna biblioteca externa. He incluido comentarios en este método.
public void resultSetToTableModel(ResultSet rs, JTable table) throws SQLException{ //Create new table model DefaultTableModel tableModel = new DefaultTableModel(); //Retrieve meta data from ResultSet ResultSetMetaData metaData = rs.getMetaData(); //Get number of columns from meta data int columnCount = metaData.getColumnCount(); //Get all column names from meta data and add columns to table model for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++){ tableModel.addColumn(metaData.getColumnLabel(columnIndex)); } //Create array of Objects with size of column count from meta data Object[] row = new Object[columnCount]; //Scroll through result set while (rs.next()){ //Get object from column with specific index of result set to array of objects for (int i = 0; i < columnCount; i++){ row[i] = rs.getObject(i+1); } //Now add row to table model with that array of objects as an argument tableModel.addRow(row); } //Now add that table model to your table and you are done :D table.setModel(tableModel); }
El constructor de JTable acepta dos argumentos de 2dimension Object Array para los datos y String Array para los nombres de las columnas.
p.ej:
import java.awt.BorderLayout; import java.awt.Color; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; public class Test6 extends JFrame { public Test6(){ this.setSize(300,300); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Mpanel m = new Mpanel(); this.add(m,BorderLayout.CENTER); } class Mpanel extends JPanel { JTable mTable; private Object[][] cells = {{"Vivek",10.00},{"Vishal",20.00}}; private String[] columnNames = { "Planet", "Radius" }; JScrollPane mScroll; public Mpanel(){ this.setSize(150,150); this.setComponent(); } public void setComponent(){ mTable = new JTable(cells,columnNames); mTable.setAutoCreateRowSorter(true); mScroll = new JScrollPane(mTable); this.add(mScroll); } } public static void main(String[] args){ new Test6().setVisible(true); } }
Este es mi enfoque:
String[] columnNames = {"id", "Nome", "Sobrenome","Email"}; List students = _repo.getAll(); Object[][] data = new Object[students.size()][4]; int index = 0; for(Student s : students) { data[index][0] = s.getId(); data[index][1] = s.getFirstName(); data[index][2] = s.getLastName(); data[index][3] = s.getEmail(); index++; } DefaultTableModel model = new DefaultTableModel(data, columnNames); table = new JTable(model);
ir aquí blog de consejos de java
luego, ingrese su proyecto: listtabelmodel.java y rowtablemodel.java agreguen otra clase con este código:
enter code here /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package comp; import java.awt.*; import java.sql.*; import java.util.*; import javax.swing.*; import static javax.swing.JFrame.EXIT_ON_CLOSE; import javax.swing.table.*; public class TableFromDatabase extends JPanel { private Connection conexao = null; public TableFromDatabase() { Vector columnNames = new Vector(); Vector data = new Vector(); try { // Connect to an Access Database conexao = DriverManager.getConnection("jdbc:mysql://" + "localhost" + ":3306/yourdatabase", "root", "password"); // Read data from a table String sql = "select * from tb_something"; Statement stmt = conexao.createStatement(); ResultSet rs = stmt.executeQuery(sql); ResultSetMetaData md = rs.getMetaData(); int columns = md.getColumnCount(); // Get column names for (int i = 1; i <= columns; i++) { columnNames.addElement(md.getColumnName(i)); } // Get row data while (rs.next()) { Vector row = new Vector(columns); for (int i = 1; i <= columns; i++) { row.addElement(rs.getObject(i)); } data.addElement(row); } rs.close(); stmt.close(); conexao.close(); } catch (Exception e) { System.out.println(e); } // Create table with database data JTable table = new JTable(data, columnNames) { public Class getColumnClass(int column) { for (int row = 0; row < getRowCount(); row++) { Object o = getValueAt(row, column); if (o != null) { return o.getClass(); } } return Object.class; } }; JScrollPane scrollPane = new JScrollPane(table); add(scrollPane); JPanel buttonPanel = new JPanel(); add(buttonPanel, BorderLayout.SOUTH); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { JFrame frame = new JFrame("any"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create and set up the content pane. TableFromDatabase newContentPane = new TableFromDatabase(); newContentPane.setOpaque(true); //content panes must be opaque frame.setContentPane(newContentPane); //Display the window. frame.pack(); frame.setVisible(true); } }); } }
luego arrastre esta clase a su jframe, y ya está hecho
está en desuso, pero funciona .........
Tienes que descargar el tarro llamado rs2xml haciendo clic en este enlace rs2xml.jar. Luego agrégalo a tus bibliotecas de proyectos y luego importa
Con todos los factores puestos en consideración, con respecto a la architecture del código, el uso de progtwigción modular funcionaría muy bien y con más simplicidad en el código. Escribe un simple
getData() function @returns a 2D array of the data from the database.
pase esta función al constructor del constructor JTabel (), es decir,
JTabel myTable = new JTable(getData(),columnsArray);
En este caso, el segundo argumento: columnsArray es una única matriz dimensional que tiene los nombres de las columnas