简体   繁体   中英

retrieving data from mysql and putting it on JTables

I'm trying to write a java program that first asks you for username and password, which are then used to connect to the database. That works fine so far. Now the program is like a customer/client organizer. it has the names and information of like address date that the customer joined, phone number etc etc. Then you click a customer and you can see any notes on them. But thats not the problem now.

what im trying to do is getting the information from my table which is in mysql database and display it in java with JTable. then at the same time i edit that information in the JTable, it also updates the database. any advice on how to do this would be thanked. Tutorials would be even better. thanks in advance..

You can build the table using a Table Model created by manipulating a Result Set. You can probably use something like this, assuming that you're using the JDBC and you already understand how to use result sets... :

JTable table = new JTable(writeResult(res));


public static DefaultTableModel writeResult (ResultSet res) throws SQLException {

    ResultSetMetaData metaData = res.getMetaData();

    Vector<String> columnNames = new Vector<String>();
    int columnCount = metaData.getColumnCount();
    for (int column = 1; column <= columnCount; column++) {
        columnNames.add(metaData.getColumnName(column));
    }

    Vector<Vector<Object>> data = new Vector<Vector<Object>>();
    while (res.next()) {
        Vector<Object> vector = new Vector<Object>();
        for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
            vector.add(res.getObject(columnIndex));
        }
        data.add(vector);
    }
    return new DefaultTableModel(data, columnNames);
}

Edit: If this doesn't help, there are many questions that already exist on Stack in which you can reference... Please try and check to see if your question has already been answered before asking it! You can check this:

Retrieve Data from MySQL DB and show in JTable

Or this:

https://stackoverflow.com/search?q=fill+jtable+from+mysql

Well here is some code that should bring you further.. Didn't test it, but it gives you the general idea.

ArrayList<String[]>  tableData=new ArrayList<>(); // you need a dynamic sized container for the results
ResultSet rs = statement.executeQuery( "SELECT * FROM Customer" );  // query the database

while ( rs.next() ){  // loop through the resultset as long as there is a next row
    tableData.add(new String[]{rs.getString("customerFirstName"), rs.getString("customerLastName"}); // for each row add a String[] with your data from the db
}

String[][] tableRows = tableData.toArray(new String[tableData.size()][]); // convert the ArrayList to a regular Array

String[] columnNames =  {
  "First Name", "Last Name"  // name your table columns
};

JFrame f = new JFrame();    // you need a window to display the JTable
f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 

JTable table = new JTable( tableRows, columnNames );   // thats how you put the data into the JTable
f.add( new JScrollPane( table ) );  // add the JTable to the window

f.pack();
f.setVisible( true );   // finished

Now all you have to figure out is how to check for changes in the table (when someone edits something) and how to write the changes back to the database . Have a look at the Oracle Docs to find more information.

This will help you to get data from database and display it on jtable .

//Global Declaration

private Vector<Vector<String>> data; //used for data from database
private Vector<String> header; //used to store data header

//Display info to JTable

data = get();

//create header for the table
header = new Vector<String>();
header.add("Column1"); 
header.add("Column2");
...
model=new DefaultTableModel(data,header);
table = new JTable(model);

This will help you to get data from database

get(){
Vector<Vector<String>> doublevector = new Vector<Vector<String>>();

Connection conn = dbConnection();//Your Database connection code
PreparedStatement pre1 = conn.prepareStatement("select * from Table");

ResultSet rs1 = pre1.executeQuery();
while(rs1.next())
{
Vector<String> singlevector = new Vector<String>();
singlevector.add(rs1.getString(1)); 
singlevector.add(rs1.getString(2)); 
....
doublevector.add(singlevector);

}

return doublevector;
}

To update your database you can use the button and then you should write the code on button's ActionListener() method.

Just create one button.

JButton update=new JButton("Update");

Use ActionListener

update.addActionListener(this);

use actionPerformed() method

@Override
public void actionPerformed(ActionEvent ae){
    if(ae.getSource()==update){
        int row = table.getSelectedRow();
        //Database connection

        //Get values from JTable

        val1 = table.getValueAt(row,0).toString();
        val2 = table.getValueAt(row,1).toString();
        val3 = table.getValueAt(row,2).toString();

        //Fire update query
    }
});

Useful Links

  1. JDBC - Update Records Example
  2. Using Prepared Statements

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM