📄 connectdatabase2.java
字号:
package scwcd.ch04;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.sql.*;
public class ConnectDatabase2 extends HttpServlet {
Connection conn = null;
String targetDB;
int cannotConnect = 0;
public void init() throws ServletException {
ServletContext context = getServletContext();
String driver_type = context.getInitParameter("driver_type");
String url = context.getInitParameter("url");
String username = context.getInitParameter("username");
String passwd = context.getInitParameter("passwd");
try{
// 1. 注册 Oracle JDBC 驱动程序
Class.forName(driver_type);
// 2. 建立新数据库连接
conn = DriverManager.getConnection(url, username, passwd);
DatabaseMetaData md = conn.getMetaData();
targetDB = md.getDatabaseProductName();
}
catch (ClassNotFoundException e) {
cannotConnect = 1;
}
catch (SQLException e){
cannotConnect = 2;
}
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
if (cannotConnect ==1) {
out.println("Cannot load the specified JDBC driver... ");
}
else {
if (cannotConnect ==2) {
out.println("Cannot create database connection...");
}
else {
try{
// 3. 建立 Statement 对象
Statement stmt = conn.createStatement ();
// 4. 执行 SELECT 命令,查询结果存放在 rset 对象
ResultSet rset = stmt.executeQuery ("SELECT * FROM emp");
// 5. 取得 rset 结果集相关信息
ResultSetMetaData md = rset.getMetaData();
// 6. 取得 ResultSet 对象内栏位数量
int no_cols = md.getColumnCount();
String[] col_names = new String[no_cols];
// 7. 取得 ResultSet 对象内各栏位名称
for(int i = 0; i < no_cols; i++)
col_names[i] = md.getColumnLabel(i+1);
out.println("<table border=1>");
// 8. 取得 ResultSet 对象内各栏位名称
out.println("<tr>");
for(int i = 0; i < no_cols; i++){
out.println("<td bgcolor=#009999>");
out.println("<font color=#FFFFFF>");
out.println(col_names[i] +"</font></td>");
}
out.println("</tr>");
// 9. 显示每条数据列内各栏位数据
while (rset.next()) {
out.println("<tr>");
for(int i = 1; i <= no_cols; i++){
out.println("<td>" + rset.getString(i) +"</td>");
}
out.println("</tr>");
}
out.println("</table>");
rset.close();
stmt.close();
} catch(Exception e){}
}
}
out.println("</html></body>");
out.close();
}
public void destroy() {
try {
conn.close();
} catch(SQLException e){}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -