How to display MySQL data in JTable without using vector? - java

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

Related

Java Jtable searching

When I am typing in jtable row I need to get suggestions to that table rows(filtered) from mysql data base and select from it (like Invoice generating as picture )I need to develop as below picture and here is the code I coded so far
jdbc j = new jdbc();
DefaultTableModel dt = (DefaultTableModel) tab_reta_in.getModel();
int row = tab_reta_in.getSelectedRow();
int col = tab_reta_in.getSelectedColumn();
Data_feild = (String) tab_reta_in.getValueAt(row, col);
int Def_r = row;
if (col == 0) {
try {
ResultSet rs = j.GetData("select * from invoice_retails where name like '" + Data_feild + "%' ");
while (rs.next()) {
String col0 = rs.getString("medi_id");
String col1 = rs.getString("name");
String col2 = rs.getString("prize");
Object[] rows = {col0, col1, col2};
dt.addRow(rows);
}
} catch (Exception ex) {
System.out.println(ex);
}

search between dates how to show in jtable

Here is code, i am using 2 jdatechooser and i put the codes in a button. I am also not sure if the query is correct.
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url="jdbc:sqlserver://USER-PC:1433;databaseName=tblgg";
String userr="sa";
String passs="1234";
Connection con=DriverManager.getConnection(url,userr,passs);
java.util.Date first = dt1.getDate();
java.util.Date second = dt2.getDate();
String sql="SELECT * FROM tbl_sale WHERE date between '"+ first+"'and
'"+second+"'";
PreparedStatement pst= con.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
tblsale.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
Okay i edit my code. xD now something is happening but nothing is showing up.
To correct your lack of prepared statement usage. Try this
Resuse your connection
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url="jdbc:sqlserver://USER-PC:1433;databaseName=tblgg";
String userr="sa";
String passs="1234";
Connection con=DriverManager.getConnection(url,userr,passs);
ResultSet result = null;
String sql2 = "select\n" +
"*\n" +
"from student\n" +
"where date(first) > ? and date(second) < ?";
PreparedStatement ps1 = con.prepareStatement( sql2, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY) ;
ps1.setObject (1 , startDatePicker.getModel().getValue());
ps1.setObject (2 , endDatePicker.getModel().getValue());
result = ps1.executeQuery();
// get number of rows
result.last();
numRows = result.getRow();
result.first();
//Get metadata object for result
ResultSetMetaData meta = result.getMetaData();
// create an arry of string for the colum names
colNames = new String[meta.getColumnCount()];
// store column names in the new col names array
for( int i = 0; i< meta.getColumnCount(); i++)
{
//get column name
colNames[i] = meta.getColumnLabel(i+1);
}
// create 2 d string array for table data
tableData = new String [numRows][meta.getColumnCount()];
// store columns in the data
for ( int row = 0 ; row < numRows; row++)
{
for (int col = 0; col < meta.getColumnCount(); col++)
{
tableData[row][col]= result.getString(col + 1);
}
result.next();
}
// close statement
ps1.close();
connection.close();
System.out.println("Data Table Loaded.");
}
To show the created result data set you use these lines
JTable table = new JTable(tableData,colNames);
JScrollPane scrollPane = new JScrollPane(table);
Don't forget to add the scroll pane to your JPanel
panel.add(scrollPane);

Populate jtable from multiple MS Access databases

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

JTable getting values form MySQL Database

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!");
}

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

Categories

Resources