0

Good day!

I would like to ask on how to transfer the contents of JTable to mySQL database. I have seen a lot of codes of putting contents to JTable from database but I need to know the other way around. ^^" I do not have any idea on how to start it.

Thanks for the help.

2
Contributors
1
Reply
4
Views
4 Years
Discussion Span
Last Post by sciwizeh
0

Do you have any code? Are you already connected to the database? If so you can use the table model to insert each row into your database:

TableModel m = table.getModel();
String SQL = "insert into YOUR_TABLE (";
for(int i =0; i<m.getColumnCount()-1; i++){
    SQL+="'"+m.getColumnName(i)+"',";
}
SQL+="'"+m.getColumnName(m.getColumnCount()-1)+"') values ";
for(int row = 0; row<m.getRowCount(); row++){
    SQL+="(";
    for(int col = 0; col<m.getColumnCount()-1; col++){
        SQL+=m.getValueAt(row,col);
    }
    SQL+=m.getValueAt(row,m.getColumnCount()-1)+")";
    if(row<m.getRowCount()-1){
        SQL+=",";
    }
}
//SUBMIT QUERY using sql

NOTE: I did not attempt to compile the above code and it may not work properly or produce a syntatically correct mySQL query.

the above code assumes that the JTable column names are the same as your DB column names and that all the rows in the JTable will be new to the DB, otherwise an update statement would need to be substituted for the insert. also note that there should also probably be more in the way of error checking.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.