经典的SERVLET数据库访问程序实例介绍。
import java.sql.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SimpleQuery extends HttpServlet {
// 第二步:重写service方法
public void service (HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException {
// The name of the JDBC driver to use
String driverName = “com.mysql.jdbc.Driver”;
// The JDBC connection URL
String connectionURL = “jdbc:mysql://localhost:3306/test?user=root&password=1234″;
// The JDBC Connection object
Connection con = null;
// The JDBC Statement object
Statement stmt = null;
// The SQL statement to execute
String sqlStatement =”SELECT * FROM person”;
// The JDBC ResultSet object
ResultSet rs = null;
PrintWriter out = response.getWriter();
response.setContentType(“text/html;charset=GBK” );
//out.println(“Registering ” + driverName);
try {
// Create an instance of the JDBC driver so that it has
// a chance to register itself
Class.forName(driverName).newInstance();
// Create a new database connection. We’re assuming that
// additional properties (such as username and password)
// are not necessary
con = DriverManager.getConnection(connectionURL);
// Create a statement object that we can execute queries
// with
stmt = con.createStatement();
// Execute the query
rs = stmt.executeQuery(sqlStatement);
// Process the results. First dump out the column
// headers as found in the ResultSetMetaData
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
String line = ” “;
for (int i = 0; i < columnCount; i++) {
if (i > 0) {
line += ” : “;
}
// Note that the column index is 1-based
line += rsmd.getColumnLabel(i + 1);
}
out.println(line+”<br>”);
// Count the number of rows
int rowCount = 0;
// Now walk through the entire ResultSet and get each
// row
while (rs.next()) {
rowCount++;
// Dump out the values of each row
line = “”;
for (int i = 0; i < columnCount; i++) {
if (i > 0) {
line += “: “;
}
// Note that the column index is 1-based
line += rs.getString(i + 1);
}
out.println(line+”<br>”);
}
out.println(“<hr><br>”+ rowCount + ” rows, ” +columnCount + ” columns”+”<br>”);
}
catch(Exception e)
{
}
}
}