Assumptions
1. the server has MySQL installed location with database named "DBName" and username "mysqluser"
and password "mysqlpassword"
2. there is a table named "kb"
Servlet
=======
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class ReadKB extends HttpServlet
{
private Connection conn;
public void init()
{
String driver = "com.mysql.jdbc.Driver";
try
{
// Load database driver
Class.forName(driver);
// Establish connection to database
conn = DriverManager.getConnection("jdbc:mysql://localhost/DbName","mysqluser",
"mysqlpassword");
}
catch(ClassNotFoundException cnfe)
{ }
catch(SQLException sqle)
{ }
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
// If no connection, then display server error page
if(conn == null)
{
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database
connection could not be established");
return;
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try
{
Statement statement = conn.createStatement();
String query = "SELECT * from kb";
// Send query to database obtain resultset
ResultSet rs = statement.executeQuery(query);
out.println("
");
int columns = rs.getMetaData().getColumnCount();
// display columns as table headers
out.println("\n");
for (int i=1; i<= columns; i )
{
String columnName = rs.getMetaData().getColumnName(i);
out.println("" columnName " | ");
}
out.println(" \n");
// display row data as table rows
while(rs.next())
{
// display resultset rows as table rows
out.println("\n");
for (int i=1; i<= columns; i )
{
String columnName = rs.getMetaData().getColumnName(i);
String columnValue = rs.getString(i);
out.println("" columnValue " | ");
}
out.println(" \n");
}
out.println(" ");
rs.close();
statement.close();
}
catch(SQLException sqle)
{
out.println("Database error: " sqle "");
}
}
public void destroy()
{
// close connection
try
{
conn.close();
}
catch(SQLException sqle)
{ }
}
}
|