ResultSet in JTable - java

How to display ResultSet in JTable. i am using this code
String [] record= new
String[ColCount];
for (i=0; i<ColCount; i++)
{
record[i]=rset1.getString(i+1);
}
cell[i] = rset1.getString("loginname");
cell[i] = rset1.getString( "role");
System.out.println(cell[i][0]);
//ItemGroup = rset1.getString( "Status");
}
System.out.println(ItemCode);
JTable jt = new JTable(
cell[i], headers);
but I get only one row which is lastly inserted to database.

You need to put a while loop around your code to iterate over the result set. eg,
while(rset1.next())
{
//do something
}

The code that you have listed is incomplete/incomprehensible, but the code below shows how to take a ResultSet with an arbitrary number of columns and display its contents in a JTable.
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
private void viewTable(){
//Perform database query here, which will open a Connection to the database
//Assume we use the above query to populate a ResultSet results
//Get information about the ResultSet
ResultSetMetaData metaData = results.getMetaData();
//Gets the number of columns in results
int columnCount = metaData.getColumnCount();
//Gets the name of each column in results
String[] columnNames = new String[columnCount];
for(int i = 0; i < columnNames.length; i++){
columnNames[i] = metaData.getColumnLabel(i+1);
}
//You can use a String[] to keep track of the rows if you know the #
//# of rows in the ResultSet, this implementation assumes that we don't
//This ArrayList will keep track of each row in results (each row is
//represented by a String[]
ArrayList<String[]> rows = new ArrayList<>();
while(results.next()){
//Fetch each row from the ResultSet, and add to ArrayList of rows
String[] currentRow = new String[columnCount];
for(int i = 0; i < columnCount; i++){
//Again, note that ResultSet column indecies start at 1
currentRow[i] = results.getString(i+1);
}
rows.add(currentRow);
}
//Close Connection to the database here
String[][] rowsArray = new String[rows.size()][columnCount];
rowsArray = rows.toArray(rowsArray);
table = new JTable(rowsArray, columnNames);
}

Related

Retrieve data from MS Access Database and display in JTable

I am trying to get data from a database and display them into a JTable in Java.
Now I have a working code which does retrieve the data and displays it in the table but somehow it does not display the first column. Anybody an idea?
Here my code:
stmt = con.createStatement();
rs = stmt.executeQuery(Query);
while (table.getRowCount() > 0) {
((DefaultTableModel) table.getModel()).removeRow(0);
}
int columns = rs.getMetaData().getColumnCount();
while (rs.next()) {
Object[] row = new Object[columns];
for (int i = 1; i <= columns; i++) {
row[i-1] = rs.getObject(i);
}
((DefaultTableModel) table.getModel()).insertRow(rs.getRow() - 1, row);
}
rs.close();
stmt.close();
con.close();
UPDATE
Ok I tried using Vector and it happens the same thing. My database has the following columns: ID, Subject, AS1, AS2
Now I do get the data displayed in the JTable, but the order of my row data always starts with the Subject column first, then AS1, then AS2 and last ID.
Why is this happening?
I have found a way around it by creating another Object[] and assigning the last object from the first array to the first of array two.
while (rs.next()) {
Object[] row = new Object[columns];
for (int i = 1; i <= columns; i++) {
row[i-1] = rs.getObject(i);
}
Object sub = row[0];
Object ses = row[1];
Object as1 = row[2];
Object as2 = row[3];
Object as3 = row[4];
Object fe = row[5];
Object id = row[6];
Object[] row2 = new Object[columns];
row2[0] = id;
row2[1] = sub;
row2[2] = ses;
row2[3] = as1;
row2[4] = as2;
row2[5] = as3;
row2[6] = fe;
((DefaultTableModel) table.getModel()).insertRow(rs.getRow() - 1, row2);
}
Not beautiful but it gets the job done.

Add/Delete Data from Database in JTable improperly

I create Jtable that store data from the database that I can delete/add contents' the Jtable with Jbutton. When I t try to run the code, I got this result:
When I add data into Jtable twice,there is data in it with an extra blank row
When I delete data into Jtable twice,data in a specific row is deleted but it add a transparent blank row too.
Why does this happen?
Here the code that I think there is a problem:
//add,delete button
final JToggleButton tglbtnAdd = new JToggleButton("Add");
final JToggleButton tglbtnDelete = new JToggleButton("Delete");
JButton button = new JButton("1");
button.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent arg0) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection dbconbt1 = DriverManager.getConnection("" +"jdbc:sqlserver://localhost;databaseName=Store;user=sa;password=");
Statement sqlstatement = dbconbt1.createStatement();
ResultSet dbresultset1 = sqlstatement.executeQuery("select * from Store.dbo.Product where ProductID = 'P-1'");
ResultSetMetaData rsmetadata = dbresultset1.getMetaData(); // Get metadata on them
int numcols = rsmetadata.getColumnCount(); // How many columns?
// Get column names
for (int i = 1; i <= numcols; i++) {
defaultmodel2.addColumn( rsmetadata.getColumnName(i));
}
if(tglbtnAdd.isSelected() == true) {
while (dbresultset1.next()) {
Vector<Object> row = new Vector<Object>(numcols);
for (int i = 1; i <= numcols; i++) {
row.addElement( dbresultset1.getObject(i) );
}
defaultmodel2.addRow(row );
}
}
if(tglbtnDelete.isSelected() == true) {
/**while (dbresultset1.next())
{
Vector<Object> row = new Vector<Object>(numcols);
row.removeElement( dbresultset1.getObject(0) );
}
*/
defaultmodel2.removeRow(0);
}
// Get row
dbresultset1.close();
sqlstatement.close();
dbconbt1.close();
Make your table structure on form load only, and just take your data from JTextField's (or from whatever you use) into Object array. Finally, add the object array to your model. For delete, just call model.removeRow() method.

Fill a Swing table with some data from MySQL DB

I need to fill a Swing table with some data from MySQL DB. The problem is that the table does not display all the columns (i.e. a.aircraftType and b.aircraftCategory). In Debug mode I checked that the query returns correct data. So, why finally some columns are not displayed?
private JTable tbArrivals;
private QueryTableModelFS mdArrivals;
mdArrivals = new QueryTableModelFS();
tbArrivals = new JTable(mdArrivals);
private void fillArrivals() {
mdArrivals.setHost(url); mdArrivals.setDB(db); mdArrivals.setLogin(login); mdArrivals.setPassw(passw);
String query;
query = "SELECT a.id,a.flightNum_arr,a.from_ICAO,a.ETA,a.pkId,a.aircraftType,b.aircraftCategory " +
"FROM flightschedule a, aircrafts b " +
"WHERE a.aircraftType = b.aircraftType;";
mdArrivals.setQuery(query);
}
public void setQuery(String query) {
cache = new Vector();
try {
// Execute the query and store the result set and its metadata
Connection con = getConnection();
Statement statement = con.createStatement();
ResultSet rs = statement.executeQuery(query);
ResultSetMetaData meta = rs.getMetaData();
colCount = meta.getColumnCount();
// Rebuild the headers array with the new column names
headers = new String[colCount];
for (int h = 1; h <= colCount; h++) {
headers[h - 1] = meta.getColumnName(h);
}
while (rs.next()) {
String[] record = new String[colCount];
for (int i = 0; i < colCount; i++) {
record[i] = rs.getString(i + 1);
}
cache.addElement(record);
}
fireTableChanged(null);
rs.close();
if (con.getAutoCommit() != false) {
con.close();
}
} catch (Exception e) {
cache = new Vector();
e.printStackTrace();
}
}
I can't tell what how your TableModel works (it looks like you might be using the DefaultTableModel), but I would suggest using Vectors instead of Arrays to get the data from your ResultSet. Right now your code is very confusing. In one loop you are using (i - 1) to access the data. In the next loop you are using (i + 1). I know the reason is because Arrays are 0 based and the ResultSet is 1 based.
When you use a Vector your loops can just start with 1 and then you just use the addElement() method to add the data to the Vector so your code is not concerned with matching indexes.
See Table From Database Example in Table From Database.

How to load the JTable faster?

I have created 2 JTable in my class,
for the first JTable the data comes from server to arraylist and then to JTable
for the second JTable the data comes from local access database to JTable (no arraylist)
Both JTables will be displayed together when user click a button.
But it takes up to 1min to load and display both jtable on the interface.
Is there any way to load them faster?
Sample code Table1
data = new ArrayList<Person>();
try
{
conn = dc.getConnection();
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
while(rs.next())
{
String[] rowData = new String[4];
for(int i=1;i<=4;i++)
{
rowData[i-1] = rs.getString(i);
}
//database to arraylist
data.add(new Person(rowData[0],rowData[1],rowData[2],rowData[3]));
}
String[] colNames = {"LastName","FirstName","Email","Department"};
model = new DefaultTableModel(colNames,data.size())
sorter = new TableRowSorter<TableModel>(model);
int row = 0;
//arraylist to JTable
for(Person p:data)
{
model.setValueAt(p.lastName, row, 0);
model.setValueAt(p.firstName, row, 1);
model.setValueAt(p.email, row, 2);
model.setValueAt(p.dept, row, 3);
row++;
}
table.setModel(model);
table.setRowSorter(sorter);
Sample code of Table2
String[] colNames = {"Name","Email","Department","Status"};
model = new DefaultTableModel(colNames,500);
table.setModel(model);
try
{
conn = ac.getConnection();
stmt = conn.prepareStatement(insert);
rs = stmt.executeQuery();
int row = 0;
while(rs.next())
{
String[] rowData = new String[4];
for(int i=1;i<=4;i++)
{
rowData[i-1] = rs.getString(i);
}
//access database to jTable
model.setValueAt(rowData[0], row, 0);
model.setValueAt(rowData[1], row, 1);
model.setValueAt(rowData[2], row, 2);
model.setValueAt(rowData[3], row, 3);
row++;
}
The delay is caused by the time required to do the database queries. So you want to make sure you are doing two separate queries, each on a different thread so one query is not waiting for the other to finish.
This can be done by creating 2 SwingWorkers, one for the server access and the other for the local access.
you can load data to jtable easily through this
DefaultTableModel tm = (DefaultTableModel) jTable1.getModel();
tm.addRow(new Object[] {name,age,tel});
name age tel are values in column1, column2, column3

JTable swing import database sql

Could someone provide me with an example or tutorial on how to import a data from a mysql database within a JTable within the use of a GUI. I tried looking for an example but have not found anything.
Hopefully we can put this question to rest
Connection db = DriverManager.getConnection( jdbc:mysql://192.168.0.3:3306,<user>,<password>);
Statement stmt = db.createStatement();
PreparedStatement psmt = con.prepareStatement("SELECT * FROM DB");
ResultSet rs = psmt.executeQuery();
// get column names
int len = rs.getMetaData().getColumnCount();
Vector cols= new Vector(len);
for(int i=1; i<=len; i++) // Note starting at 1
cols.add(rs.getMetaData().getColumnName(i));
// Add Data
Vector data = new Vector();
while(rs.next())
{
Vector row; = new Vector(len);
for(int i=1; i<=len; i++)
{
row.add(rs.getString(i));
}
data.add(row);
}
// Now create the table
JTable table = new JTable(data, cols);

Categories

Resources