We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,654 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

How to transfer contents of JTable to mySQL database

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 Days
Discussion Span
1 Year Ago
Last Updated
2
Views
chixm8_49
Light Poster
46 posts since Aug 2009
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 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.

sciwizeh
Posting Pro in Training
487 posts since Jun 2008
Reputation Points: 77
Solved Threads: 25
Skill Endorsements: 0

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.0786 seconds using 2.67MB