I am using netbeans IDE. I like to check how canni actually search from a jtable which is mapped to a table using netbeans binding. I want to refresh the jtable showing records that matches my search criteria
DefaultTableModel model = new DefaultTableModel( results from your search );
table.setModel( model );
Edit: See Table From Database.
First i get the field names in a Jcombo box.
private void Text1KeyReleased(java.awt.event.KeyEvent evt) {
JTetclear();
Connection con = null;
Statement stmt = null;
try {
con = javaconnect.MySqlServer();
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM `" + Combo1.getSelectedItem() + "` where `" + Combo2.getItemAt(0).toString() + "` Like '%" + Text1.getText() + "%' or `" + Combo2.getItemAt(1).toString() + "` Like '%" + Text1.getText() + "%' or `" + Combo2.getItemAt(2).toString() + "` Like '%" + Text1.getText() + "%' or `" + Combo2.getItemAt(0).toString() + "` Like '%" + Text1.getText() + "%' order by PARTNO;");
ResultSetMetaData md = rs.getMetaData();
DefaultTableModel tm = (DefaultTableModel) Table1.getModel(); // for changing column and row model
Combo2.removeAllItems();
tm.setColumnCount(0); tm.setRowCount(0); // clear existing columns and clear existing rows
for (int i = 1; i <= md.getColumnCount(); i++) {
tm.addColumn(md.getColumnName(i));
Combo2.addItem(md.getColumnName(i));//l load the column name in the combobox
}
tm.setRowCount(0); // clear existing rows
while (rs.next()) { // Get row data
Vector row = new Vector(md.getColumnCount());
for (int i = 1; i <= md.getColumnCount(); i++) {
row.addElement(rs.getObject(i));
}
tm.addRow(row);
Table1.getColumnModel().getColumn(0).setPreferredWidth(160);
Table1.getColumnModel().getColumn(1).setPreferredWidth(380);
}
rs.close();
stmt.close();
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, ex, ex.getMessage(), WIDTH, null);
}
}
This is how i did it. Not an expert.
A method that returns result set:
public ResultSet actualInventoryInCencos(int idCencos) throws SQLException {
try {
SQL sql = new SQL();
PreparedStatement selectPS = sql.createPStatement(cf.SELECT_INVENTORY_BY_CENCOS);
selectPS.setInt(1, idCencos);
ResultSet resultSet = selectPS.executeQuery();
return resultSet;
} catch (SQLException | NullPointerException e) {
System.out.println(cf.ERROR_SQL + e);
cf.e(1);
return null;
}
}
Method in TableDAO that accepts the result set and make and returns a DefaultTableModel with all the query data.
public DefaultTableModel createTable(ResultSet rs) throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
//ColumnsNames
Vector<String> columnsNames = new Vector<>();
columnsNames.add("Column1");
columnsNames.add("Column2");
columnsNames.add("Column3");
Vector<Vector<Object>> tableData = new Vector<>();
while (rs.next()) {
Vector<Object> vector = new Vector<>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
tableData.add(vector);
}
return new DefaultTableModel(tableData, columnsNames);
}
And the line to set the New Model to your JTable:
yourJTable.setModel(tableDAO.createTable(inventory.actualInventoryInCencos(userData.getUserId())));
Related
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);
}
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);
try {
DataBase DB = new DataBase();
Connection con = DB.Connect();
String sql;
sql = "select Id,Name,FatherName, City, Address, Department,RStatus, DatePlacement\n"
+ "from ECL where "
+ "id like ? and "
+ "name like ? and FatherName like ? and "
+ "City like ? and Address like ?";
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1, "%" + SearchId.getText() + "%");
pst.setString(2, "%" + SearchName.getText() + "%");
pst.setString(3, "%" + SearchFatherName.getText() + "%");
pst.setString(4, "%" + SearchCity.getText() + "%");
pst.setString(5, "%" + SearchAddress.getText() + "%");
ResultSet rs = pst.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int MetaColum = rsmd.getColumnCount(); //adding colums in Jtable
Vector col = new Vector();
for (int i = 1; i <= MetaColum; i++) {
col.addElement(rsmd.getColumnName(i));
}
ReTable.setColumnIdentifiers(col);
while (rs.next()) {
Vector rows = new Vector(); // to add rows in Jtable
for (int j = 1; j <= MetaColum; j++) {
rows.addElement(rs.getString(j));
}
ReTable.addRow(rows);
ResultTable.setModel(ReTable);
}
} catch (Exception ex) {
System.out.println(ex);
}
ReTable.fireTableDataChanged(); // Method to refresh the Jtable
}
how to refresh jtable with new data. it loads new data but it also contain the old data every time i search for new name it give me the correct result but the previous search data also remains in jtable. my question is how to refresh jtable every time i make a new search. Thanks In Advance.
You are not removing the previous rows inserted in your model ReTable. In each call you are adding more and more rows in this line:
ReTable.addRow(rows);
Remove all rows from the model before launching the query or create a new model fresh with no rows for each query.
currently I have data in MySQL server and I am calling the datas onto the JTable through JDBC. However there are 1369 rows and it seems that it has too much data for it to load. It usually takes 5 minutes to load. Are there anyways to optimize the process? This is my code(I apologize in advance for a messy code):
public class DataTable {
private String databaseName = "*****";
private String tableName = "******";
public void showDatabase(){
Connection conn = null;
DatabaseMetaData meta = null;
Statement stmt = null;
ResultSet rs = null;
int k = 0;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String connectionUrl = "jdbc:mysql://localhost:3306/" + databaseName;
String connectionUser = "*****";
String connectionPassword = "*****";
conn = DriverManager.getConnection(connectionUrl, connectionUser, connectionPassword);
stmt = conn.createStatement();
meta = conn.getMetaData();
dataSets(stmt, meta);
}catch(Exception e){
e.printStackTrace();
} finally{
try { if (rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (stmt != null) stmt.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); }
}
}
//return the column size of the table
public int getColumnNumber(DatabaseMetaData meta, Statement stmt) throws SQLException
{
//ResultSet rs = meta.getColumns(null, null, "practiceexample", null);
ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName);
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
return columnsNumber;
}
//return the rowNumber of the tables
public int getRowNumber(Statement stmt) throws SQLException
{
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM " + tableName);
int rowCount = 0;
while(rs.next()){
rowCount = rs.getInt(1);
}
return rowCount;
}
public void dataSets(Statement stmt, DatabaseMetaData meta) throws SQLException
{
String[] columnNames = new String[getColumnNumber(meta, stmt)];
String[][] dataSets = new String[getRowNumber(stmt)][columnNames.length];
ResultSet column = meta.getColumns(null, null, tableName, null);
int i = 0;
while(column.next())
{
columnNames[i] = column.getString("COLUMN_NAME");
//columnNames.add(i, column.getString("COLUMN_NAME"));
i++;
}
for(int j = 0; j < dataSets.length; j++)
{
String[] singleRowData = new String[columnNames.length];
ResultSet data = null;
for(int k = 0; k < columnNames.length; k++)
{
String columnName = columnNames[k];
data = stmt.executeQuery("SELECT " + columnName +
" FROM " + tableName + " LIMIT " + j + ", " + 1);
while(data.next())
{
singleRowData[k] = data.getString(columnName);
}
}
dataSets[j] = singleRowData;
}
SimpleTable table = new SimpleTable(columnNames, dataSets);
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
table.createAndShowGUI();
}
});
}
class SimpleTable{
String[] columns;
String[][] dataSets;
public SimpleTable(String[] columns, String[][] dataSets){
this.columns = columns;
this.dataSets = dataSets;
}
public void createAndShowGUI(){
JPanel gui = new JPanel(new BorderLayout(3, 3));
final JTable table = new JTable(new DefaultTableModel(dataSets, columns));
final JScrollPane scrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED
, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
Dimension dimension = table.getPreferredSize();
scrollPane.setPreferredSize(new Dimension(dimension.width, table.getRowHeight() * 30));
JPanel navigation = new JPanel(new FlowLayout(FlowLayout.CENTER));
JButton next = new JButton(">");
next.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
int height = table.getRowHeight() * (20-1);
JScrollBar bar = scrollPane.getVerticalScrollBar();
bar.setValue(bar.getValue() + height);
}
});
JButton previous = new JButton("<");
previous.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent ae) {
int height = table.getRowHeight()*(20-1);
JScrollBar bar = scrollPane.getVerticalScrollBar();
bar.setValue( bar.getValue()-height );
}
} );
navigation.add(previous);
navigation.add(next);
gui.add(scrollPane, BorderLayout.CENTER);
gui.add(navigation, BorderLayout.SOUTH);
JOptionPane.showMessageDialog(null, gui);
}
}
}
IMHO the root of the bad permormance is you unnecessarily query the database mutliple times to get the data (columns, rows, rows number, columns number, etc) you need:
To get columns number:
ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName);
To get rows number:
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM " + tableName);
To get rows (this is the worst beacuse it's inside a loop):
data = stmt.executeQuery("SELECT " + columnName + " FROM " + tableName + " LIMIT " + j + ", " + 1);
How to solve it
Just query the database once. A single ResultSet and its associated ResultSetMetaData should be enough to accomplish your goal. Additionaly, and as already suggested, use a SwingWorker to do database calls in a separate thread. For example:
final JTable table = new JTable();
SwingWorker<Void, TableModel> worker = new SwingWorker<Void, TableModel> () {
#Override
protected Void doInBackground() throws Exception {
ResultSet resultSet = stmt.executeQuery("SELECT * FROM " + tableName);
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount(); // columns number
String[] columnNames = new String[columnCount];
for (int i = 1; i <= columnCount; i++) {
columnNames[i] = metaData.getColumnName(i); // fill columns names
}
resultSet.last();
int rowCount = resultSet.getRow(); // get rows number
resultSet.beforeFirst();
Object[][] data = new Object[rowCount][columnCount];
int currentRow = 0;
while (resultSet.next()) {
for (int currentColumn = 1; currentColumn <= columnCount; currentColumn++) {
data[currentRow][currentColumn - 1] = resultSet.getObject(currentColumn); // fill data set
}
currentRow++;
}
TableModel model = new DefaultTableModel(data, columnNames);
publish(model);
return null;
}
#Override
protected void process(List<TableModel> chunks) {
TableModel model = chunks.get(0);
table.setModel(model);
}
}
worker.execute();
I am using PhpMyAdmin to save my data in database. I have a SWT table to populate with database content.
here is my code..
public static void fetchDatafromDB(String StartIndex, String FinalIndex) {
try {
Class.forName(GlobalVariables.SQL_driver).newInstance();
Connection conn = DriverManager.getConnection(GlobalVariables.DB_url + GlobalVariables.DB_name, GlobalVariables.DB_Username, GlobalVariables.DB_password);
Statement st = conn.createStatement();
String query = "SELECT `From`, `To`, `IDno`, `TimeStamp` FROM `callsheet` WHERE TimeStamp BETWEEN '" + StartIndex + "' AND '" + FinalIndex + "'";
ResultSet rs = st.executeQuery(query);
java.sql.ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
while (rs.next()) {
for (int i = 1; i <= columnsNumber; i++) {
// System.out.print(rs.getString(i));
item.setText(i, rs.getString(i));
}
// System.out.println();
}
} catch (Exception P) {
P.printStackTrace();
}
}
it worked.
Now I am getting some problem with tabling the DB content in my swt table. What my program does, is that, it sets the selected (defined by limit in program above) content of DB in one row (one by one manner) but I want the next row of DB table to be tabled in next row of SWT table. Could you suggest something about this? ! Screenshot of my swtTable
It should look something like this:
public static void fetchDatafromDB(String startIndex, String finalIndex) {
try {
Class.forName(GlobalVariables.SQL_driver).newInstance();
Connection conn = DriverManager.getConnection(GlobalVariables.DB_url + GlobalVariables.DB_name, GlobalVariables.DB_Username, GlobalVariables.DB_password);
Statement st = conn.createStatement();
String query = "SELECT `FROM`, `To`, `IDno`, `TimeStamp` FROM `callsheet` WHERE TimeStamp BETWEEN '" + startIndex + "' AND '" + finalIndex + "'";
ResultSet rs = st.executeQuery(query);
java.sql.ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
TableItem item;
while (rs.next()) {
// Create a new TableItem for each entry in the result set (each row)
item = new TableItem(table, SWT.NONE);
for (int i = 1; i <= columnsNumber; i++) {
// Populate the item (mind the index!!)
item.setText(i - 1, rs.getString(i));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}