简体   繁体   中英

Need help on how to retrieve the data from database and write it to a html file using java?

I have a mysql database with a table of 5 columns.

Now I need to get those data from that database table and view it in a html file (with table headers and table contents) using java.

Please help me with some tutorial links.

Thanks in advance!

The crucial point here is that you need to talk to the database. You will use JDBC for this, along with a MySQL driver.

The official MySQL documentation for working with Java is at http://dev.mysql.com/usingmysql/java/ and there are a few tutorials.

If you are unfamiliar with JDBC, the official Java tutorial has a section on JDBC at http://download.oracle.com/javase/tutorial/jdbc/

If you just need to write a file containing HTML this is not hard if you know the appropriate tags. If you need to do this in a servlet container, more details are needed.

Just follow the steps:

  1. Install mySql and create database for your app.
  2. Get mySql connector jar.
  3. Do a little bit coding to get connected with mySql db in your JSP page or in servlet.
  4. Query in db and retrieve appropriate data.
  5. Display that data in JSP.

MySql database in JSP : this tutorial might help you.

Here's some sample code that builds a HTML table from a JDBC query. Use it as a starting point:

// insert your JDBC URL here
Connection connection = DriverManager.getConnection("jdbc:your-db-url");
// Edit this SQL Query so it makes sense
ResultSet resultSet = connection
                        .createStatement()
                        .executeQuery("select * from yourtable");
StringBuilder sb = new StringBuilder().append("<table>\n");
int columnCount = resultSet.getMetaData().getColumnCount();
sb.append("<tr>\n");
for(int n = 1; n <= columnCount; n++){
    sb.append("\t<th>")
      .append(resultSet.getMetaData().getColumnLabel(n))
      .append("</th>\n");
}
sb.append("</tr>\n");
while(resultSet.next()){
    sb.append("<tr>\n");
    for(int n = 1; n <= columnCount; n++){
        sb.append("\t<td>")
          .append(resultSet.getString(n))
          .append("</td>\n");
    }
    sb.append("</tr>\n");

}
sb.append("</table>")
String table = sb.toString();

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