I need to get all the values from a Database and put it inside the JTable, filling all rows.
My code just puts inside the JTable only the last row and misses all previous.
Anyone got an idea of how to get all the values from the DB and insert them all in the JTable?
try{
Class.forName("com.mysql.jdbc.Driver");
conn3 = DriverManager.getConnection("jdbc:mysql://localhost/test1?user=me&password=123456");
stmt3 = conn3.createStatement();
rs3 = stmt3.executeQuery("SELECT * FROM teams");
String str1 = null,str2 = null,str3 = null,str4 = null,str5 = null;
while (rs3.next())
{
str1 = rs3.getString(1);
str2 = rs3.getString(2);
str3 = rs3.getString(3);
str4 = rs3.getString(4);
str5 = rs3.getString(5);
}
Object[][] data = {{str1,str2,str3,str4,str5}};
String[] columnNames = {"id","Name","Players","Point","Position" };
table = new JTable(data,columnNames);
table.setCellSelectionEnabled(true);
table.setColumnSelectionAllowed(true);
table.setFillsViewportHeight(true);
table.setSurrendersFocusOnKeystroke(true);
table.setBounds(10, 321, 297, 143);
frame.getContentPane().add(table);
rs3.close();
stmt3.close();
conn3.close();
}
catch (SQLException se)
{
System.out.println( "SQL Exception:" );
while( se != null )
{
System.out.println( "State : " + se.getSQLState() );
System.out.println( "Message: " + se.getMessage() );
System.out.println( "Error : " + se.getErrorCode() );
se = se.getNextException();
}
}
catch (ClassNotFoundException ex)
{
System.out.println("Error: unable to load driver class!");
}
while (rs3.next())
{
str1 = rs3.getString(1);
str2 = rs3.getString(2);
str3 = rs3.getString(3);
str4 = rs3.getString(4);
str5 = rs3.getString(5);
}
You are overwriting again and again the same variables. You should use a list or an array instead. Something like:
while (rs3.next())
{
//Given that all of your str are declared as List<String> strX = new List<String>();
str1.add(rs3.getString(1));
str2.add(rs3.getString(2));
str3.add(rs3.getString(3));
str4.add(rs3.getString(4));
str5.add(rs3.getString(5));
}
But for inserting ResultSet in a table there are plenty of tutorials.
EDIT: If you don't want to use a table model you can change the logic of your data retrieving. You must provide to the table a matrix[row][col]. Which are your rows? And which your colums?
Rows are the "nexts" of the result set, while colums are 1 to 5. You need to know how many rows are there (a bit tricky):
if (rs3.next()) {
rs3.last();
int rows = rs3.getRow();
}
rs3.beforeFirst();
Now create the matrix:
String[][] matrix = new String[rows][4]; //Your Object[][] data.
int index = 0;
while(rs3.next()){
matrix[i][0] = rs3.getString(1);
matrix[i][1] = rs3.getString(2);
matrix[i][2] = rs3.getString(3);
matrix[i][3] = rs3.getString(4);
matrix[i][4] = rs3.getString(5);
i++;
}
String[] columnNames = {"id","Name","Players","Point","Position" };
table = new JTable(matrix, columnNames);
USEFUL: Another useful (but not strictly requested) method to retrieve the object data is using customized mappings or a more complicate Object-relational mapping framework like Hibernate.
Don't use a 2D Array to hold the data. You don't know how many rows of data will be in the database, so you don't know how large to make the Array.
Check out Table From Database for a couple of different suggestions. One approach involves using Vectors so you can use the DefaultTableModel.
The OP code is using a 2d array of Objects as the data for the JTable, but never moving data into that array. We first need to count how many rows are in the table so that we can size the array:
try {
Class.forName("com.mysql.jdbc.Driver");
conn3 = DriverManager.getConnection("jdbc:mysql://localhost/test1?user=me&password=123456");
stmt3 = conn3.createStatement();
ResultSet rowCounter = stmt3.executeQuery("SELECT COUNT(*) FROM teams");
rowCounter.next();
int numRows = rowCounter.getInt(1);
stmt3.close();
Object[][] data = new Object[numRows][5];
stmt3 = conn3.createStatement();
rs3 = stmt3.executeQuery("SELECT * FROM teams");
int row = 0;
while (rs3.next()) {
data[row][0] = rs3.getString(1);
data[row][1] = rs3.getString(2);
data[row][2] = rs3.getString(3);
data[row][3] = rs3.getString(4);
data[row][4] = rs3.getString(5);
row++;
}
String[] columnNames = {"id","Name","Players","Point","Position" };
table = new JTable(data,columnNames);
table.setCellSelectionEnabled(true);
table.setColumnSelectionAllowed(true);
table.setFillsViewportHeight(true);
table.setSurrendersFocusOnKeystroke(true);
table.setBounds(10, 321, 297, 143);
frame.getContentPane().add(table);
rs3.close();
stmt3.close();
conn3.close();
}
catch (SQLException se) {
//handle this
}
catch (ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
}
Related
I successfully managed to populate jtable from an MS Access database using UcanAccess library.
What I want is to populate jtable from two databases. I have two databases, one contains table with four columns, the other contain three columns.
I want to populate jtable with seven columns from the two databases.
Code used :
public void PopulateJtable(JTable table, String table_name) {
String sql = "SELECT * from " + table_name;
DefaultTableModel dtm = (DefaultTableModel) table.getModel();
dtm.setRowCount(0);
try {
conn = DriverManager.getConnection(myDB);
state = conn.createStatement();
state.execute(sql);
ResultSet rs = state.getResultSet();
int columns = table.getColumnCount();
Vector vector = new Vector();
while (rs.next()) {
Vector row = new Vector();
for (int i = 1; i <= columns; i++) {
row.addElement(rs.getObject(i));
}
dtm.addRow(row);
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e, "ERROR !! ", 0);
} finally {
try {
state.close();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(DBEngine.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
MS Access DB Tables :
table1
table2
i want to join above tables cols in one jtable
How to display MySQL data in JTable without using vector?
I'm doing Java Swing application and I want to show reports from database. I'm using JTable to display data from database. I have tried following code but it is not displaying data from database. My database connection is also correct.
int i;
static Vector<Vector<String>> data = new Vector<Vector<String>>();
String[] columnNames = {"Registration id", "First Name", "Middle Name", "Last Name", "Address", "Dob", "Age", "Date Of Registration", "Register Rfid No."};
public AdmissionReport()
{
initComponents();
//this is the model which contain actual body of JTable
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columnNames);
//jTable1=new JTable(model);
jTable1 = new JTable();
jTable1.setModel(model);
int i1 = jTable1.getRowCount();
if (i1 > 1) {
model.removeRow(0);
i1 = i1 - 1;
}
String str = "select rid,fname,mname,lname,address,dob,age,dor,rfidtagdata from schoolrfid.registration";
Connection cn;
ResultSet rs;
Statement st;
String rid, fname, mname, lname, add, dob, age, dor, rfidtag;
try {
// Change the database name, hosty name,
// port and password as per MySQL installed in your PC.
cn = DriverManager.getConnection("jdbc:mysql://" + "localhost:3306/schoolrfid", "root", "root");
st = cn.createStatement();
rs = st.executeQuery(str);
System.out.println("connected to database.. ");
// int i=0;
while (rs.next()) {
//Vector <String> d=new Vector<String>();
rid = (rs.getString("rid"));
fname = (rs.getString("fname"));
mname = (rs.getString("mname"));
lname = (rs.getString("lname"));
add = (rs.getString("address"));
dob = (rs.getString("dob"));
age = (rs.getString("age"));
dor = (rs.getString("dor"));
rfidtag = (rs.getString("rfidtagdata"));
i = 0;
String[] data = {rid, fname, mname, lname, add, dob, age, dor, rfidtag};
model.addRow(data);
i++;
}
if (i < 1) {
JOptionPane.showMessageDialog(null, "No Record Found", "Error", JOptionPane.ERROR_MESSAGE);
}
if (i == 1) {
System.out.println(i + " Record Found");
} else {
System.out.println(i + " Records Found");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
The TableModel behind the JTable handles all of the data behind the table. In order to add and remove rows from a table, you need to use a DefaultTableModel
To create the table with this model:
JTable table = new JTable(new DefaultTableModel(new Object[]{"Column1", "Column2"}));
To add a row:
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(new Object[]{"Column 1", "Column 2", "Column 3"});
You can also remove rows by removeRow(int row) which will removes the row at row from the model.
Full details on the DefaultTableModel can be found here
Similarly from the MySQL you can add rows like as show below
DefaultTableModel memberTable = (DefaultTableModel) table.getModel();
while(rs.next())
{
memberTable.addRow(new Object[]{rs.getString('rid'),rs.getString('fname'),rs.getString('lname'),rs.getString('address'),.....});
}
Also Take a look at this answer
https://stackoverflow.com/a/17655017/1575570
As mentioned in the header I cannot get my JTable to update with a new row unless I restart the program. When I restart, the new row is there and everything is as it should be. I have tried revalidating/repainting the panel and frame, I have tried the fire methods. I'm at a loss. Thanks in advance
ActionListener (in adminGUI class) for 'Add' button:
if(source.equals(add2)){
String c = itb.getText();
int a = main.getResults();
boolean matches = Pattern.matches("[A-Z][a-z]+", c);
if(matches == true){
main.addGenre(a, c);
}
String Method(in main class) to add a row to the database table:
public static void addGenre(int a, String b){
int rowsAdded;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection connect =DriverManager.getConnection("jdbc:odbc:MovieDB");
Statement stmt = connect.createStatement();
String query = "INSERT INTO Genres (genre_id, genre_name)" + "VALUES(" + a + ", '" + b + "')";
rowsAdded = stmt.executeUpdate(query);
}catch(Exception exc){}
}
Method(also in main class) to increment the auto-increment-key column:
public static int getResults(){
int a = 0;
ResultSet ints = main.getResults("Select genre_id from Genres");
try {
while(ints.next()){
int d = ints.getInt("genre_id");
if(d>a){
a = d;
}
a++;
}
} catch (SQLException ex) {
Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
}
return a;
}
JTable details:
ResultSet rs1 = main.getResults("Select * from Genres");
JTable tab1 = new JTable(DbUtils.resultSetToTableModel(rs1));
DbUtils.resultSetToTableModel details :
public class DbUtils {
public static TableModel resultSetToTableModel(ResultSet rs) {
try {
ResultSetMetaData metaData = rs.getMetaData();
int numberOfColumns = metaData.getColumnCount();
Vector columnNames = new Vector();
// Get the column names
for (int column = 0; column < numberOfColumns; column++) {
columnNames.addElement(metaData.getColumnLabel(column + 1));
}
// Get all rows.
Vector rows = new Vector();
while (rs.next()) {
Vector newRow = new Vector();
for (int i = 1; i <= numberOfColumns; i++) {
newRow.addElement(rs.getObject(i));
}
rows.addElement(newRow);
}
return new DefaultTableModel(rows, columnNames);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
"I cannot get my JTable to update with a new row unless I restart the program."
I think what you're expecting is that when the database table update, so should your JTable. It doesn't really work like that. You need to update the TableModel, and the JTable will be automatically updated
Since resultSetToTableModel returns a DefuaultTableModel, you can use either of the two methods from DefaultTableModel:
public void addRow(Object[] rowData) - Adds a row to the end of the model. The new row will contain null values unless rowData is specified. Notification of the row being added will be generated.
public void addRow(Vector rowData) - Adds a row to the end of the model. The new row will contain null values unless rowData is specified. Notification of the row being added will be generated.
So when your are adding the data to the database, you also want to update the DefaultTableModel like this
public static void addGenre(Integer a, String b){
...
rowsAdded = stmt.executeUpdate(query);
if (rowsAdded > 0) {
DefaultTableModel model = (DefaultTableModel)tab1.getModel();
model.addRow( new Object[] { a, b });
}
}
Also noticed I changed the method signature to Integer instead of int so it will fit with the Object[] passed to addRow. The int you pass to it will get autoboxed to Integer
SIDE NOTES
Don't swallow you exception by putting nothing in the catch block. Put something meaningful that will notify you of any exceptions that may occur, like
catch(Exception ex) {
ex.printStackTrace();
}
You should also close your Connections, Statements, and ResultSets
You should use PreparedStatement instead of Statement, to avoid SQL injection.
private void resetListData() throws ClassNotFoundException, SQLException
{
Connection cne = null;
try {
Class.forName("org.sqlite.JDBC");
cne = DriverManager.getConnection("jdbc:sqlite:table.sqlite");
cne.setAutoCommit(false);
PreparedStatement psd = (PreparedStatement) cne.prepareStatement("Select * from Genres");
psd.execute();
ResultSet r = psd.getResultSet();
ResultSetMetaData rsmd = r.getMetaData();
int count = rsmd.getColumnCount();
String[] meta = new String[count];
for (int i = 0; i < count; i++)
{
String name = rsmd.getColumnName(i + 1);
meta[i] = name;
//System.out.println(name);
}
model = new DefaultTableModel(new Object[][]{}, new String[]{"name", "address"});
jTable1.setModel(model);
while (r.next())
{
Object[] row = new Object[count];
for (int i = 1; i <= count; ++i)
{
row[i - 1] = r.getString(i); // Or even rs.getObject()
}
model.addRow(row);
}
cne.close();
} catch (ClassNotFoundException | SQLException e) {
}
}
Use this code. so you can insert one row at the end of Jtable without restarting application.,
Thanks..
I made a jtable for the list of chemicals in the inventory where I can sort each columns using the following code (chemicalTable is the name of the jTable):
chemicalTable.setAutoCreateRowSorter(true);
TableRowSorter<TableModel> sorter1
= new TableRowSorter<TableModel>(chemicalTable.getModel());
chemicalTable.setRowSorter(sorter1);
Then I used a jTextfield to create a searchbox with a keyTyped Listener so that whenever the user types a certain character the table refreshes. And it usually works.
I used this code in the keyTypedListener for the searchbox:
DefaultTableModel dm = (DefaultTableModel) chemicalTable.getModel();
str = searchChemicalText.getText();
try {
String url = "jdbc:mysql://localhost/chemical inventory";
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, "root", "");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error Occurred.", "Error", JOptionPane.ERROR_MESSAGE);
}
int ctr = 0;
while (ctr < chemicalTable.getRowCount()) {
chemicalTable.getModel().setValueAt(null, ctr, 0);
chemicalTable.getModel().setValueAt(null, ctr, 1);
chemicalTable.getModel().setValueAt(null, ctr, 2);
ctr++;
}
int count = 0;
try {
Statement stmt = conn.createStatement();
String query = "Select * FROM chemicallist where name_of_reagent like '%" + str + "%'";
ResultSet rs = stmt.executeQuery(query);
if (rs.next()) {
rs = stmt.executeQuery(query);
while (rs.next()) {
String qty = null, qtyunit = null, chemstate = null, reagentName = null;
reagentName = rs.getString("name_of_reagent");
qty = rs.getString("quantity");
qtyunit = rs.getString("quantity_unit");
chemstate = rs.getString("state");
chemicalTable.getModel().setValueAt(reagentName, count, 0);
chemicalTable.getModel().setValueAt(qty + " " + qtyunit, count, 1);
chemicalTable.getModel().setValueAt(chemstate, count, 2);
if (count + 1 > chemicalTable.getRowCount() - 1) {
dm.setRowCount(chemicalTable.getRowCount() + 1);
dm.fireTableRowsInserted(0, 5);
}
count++;
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error Occurred.", "Error", JOptionPane.ERROR_MESSAGE);
}
My problem is: Whenever I sort first any columns (col1, col2, or col3) and I insert a character in the searchbox, I got this error message:
"Exception occurred during event dispatching:
Java.lang.NullPointerException"
Although it's not possible to debug your code fragments, several things stand out:
In the same section, you reference the TableModel as dm and chemicalTable.getModel(); use a single reference or verify that they refer to the same instance.
Instead of meddling with setRowCount(), use one of the addRow() methods.
The DefaultTableModel methods that alter the model fire the correct event for you and the table will automatically update itself accordingly; you shouldn't have to do this yourself.
I have a problem regarding my JTable, I don't know how can I store my fetch records which is of type String from my database to the multidimensional array which is let's say Object[][] data. What I want to do is show my database records to the JTable, I already fetch the records in dtabase and store it in my String variables, The question is how can I store the fetch records to the multidimensional array of Object and use it on my JTable.
Here are my code for fetching records:
static class TableData{
Object[][] data;
int count = 0;
Statement sql = null;
String query, user = "JEROME", pass = "Perbert101", driver = "oracle.jdbc.OracleDriver", conString = "jdbc:oracle:thin:#127.0.0.1:1521:XE";
Connection con = null;
ResultSet rs = null;
TableData(){
try{
Class.forName(driver);
}
catch(ClassNotFoundException e){
JOptionPane.showMessageDialog(null, "Problem Loading Driver");
}
try{
con = DriverManager.getConnection(conString, user, pass);
sql = con.createStatement();
sql.executeQuery("SELECT * FROM INVENTORY");
rs = sql.getResultSet();
int key = 0;
String val = null, val1 = null, val2 = null, val3 = null, val4 = null, val5 = null;
System.out.println("Results: ");
while(rs.next()){
key = rs.getInt(1);
if(rs.wasNull()){
key = -1;
}
val = rs.getString(2);
if(rs.wasNull()){
val = null;
}
val1 = rs.getString(3);
if(rs.wasNull()){
val = null;
}
val2 = rs.getString(4);
if(rs.wasNull()){
val = null;
}
val3 = rs.getString(5);
if(rs.wasNull()){
val = null;
}
val4 = rs.getString(6);
if(rs.wasNull()){
val = null;
}
val5 = rs.getString(7);
if(rs.wasNull()){
val = null;
}
System.out.println("Key = " + key);
System.out.println("value = " + val);
System.out.println("value = " + val1);
System.out.println("value = " + val2);
System.out.println("value = " + val3);
System.out.println("value = " + val4);
System.out.println("value = " + val5);
}
sql.close();
con.close();
}
catch(SQLException e){
JOptionPane.showMessageDialog(null, "Error Loading Database Data");
}
}
}
//----------END------------
public static void main(String[] args){
POSModel.TableData data = new POSModel.TableData();
}
I'd suggest that the data you're pulling from the database needs to be stored in an array (by columns) first...
Object[] rowData = new Object[7];
rowData[0] = key;
rowData[1] = val;
rowData[2] = val1;
rowData[3] = val2;
rowData[4] = val3;
rowData[5] = val4;
rowData[6] = val5;
This then needs to be stored in some kind of row structure, I'd personally use a List. The main reason for this choice is that you probably don't know in advance the number of rows you will be reading...
List<Object[]> rowList = new ArrayList<Object[]>(25);
// Process the resultset...
// Create the column array from above...
rowList.add(rowData);
Once you've completed reading all the rows, you need to convert the list it an array...
data = rowList.toArray(new Object[](rowList.size())); // I like to provide my own array
Equally, you could do...
data = new Object[rowList.size()][7];
rowList.toArray(data);
Which ever is more convenient...
Now you should have a 2D array...