JSP访问数据库

经常看到有人问JSP关于访问数据库的问题

JSP访问数据库的方法其实和servelet访问数据库一样,只是有一些语法上的区别
通常在访问数据库时要注意以下几点:
1.数据库安装时编码应该设置为gb2312避免遇到汉字变成?的问题
2.jsp页面字符编码设置 charset=gb2312 防止页面显示汉字为乱码
3.注意out.printn()输出是否正确。

[java]  view plain copy
  1. <%@ page language="java" contentType="text/html; charset=gb2312"  
  2.  pageEncoding="gb2312"%>  
  3. <%@ page import="java.io.*"%>  
  4. <%@ page import="java.sql.*"%>  
  5. <%@ page import="java.util.*"%>  
  6. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  7. <html>  
  8. <head>  
  9. <meta http-equiv="Content-Type" content="text/html; charset=gb2312">  
  10. <title>DBACCESS</title>  
  11. </head>  
  12. <body>  
  13. <%  
  14.  ResultSet rs = null;  
  15.  Statement stmt = null;  
  16.  Connection conn = null;  
  17.  try {  
  18.   Class.forName("com.mysql.jdbc.Driver");  
  19.   String url = "jdbc:mysql://localhost/BookDB?";  
  20.   String user = "root";  
  21.   String pw = "123456";  
  22.   conn = DriverManager.getConnection(url, user, pw);  
  23.   stmt = conn.createStatement();  
  24.   //stmt.executeUpdate("insert into BOOKS values('999','TOM''TomCAT',44,5,'TOMCAT1',80000)");  
  25.   rs = stmt.executeQuery("select ID,NAME,TITLE,PRICE from BOOKS");  
  26.   out.println("<table border=1 width=400>");  
  27.   while (rs.next()) {  
  28.    String col1 = rs.getString(1);  
  29.    String col2 = rs.getString(2);  
  30.    String col3 = rs.getString(3);  
  31.    float col4 = rs.getFloat(4);  
  32.   
  33.    out.println("<tr><td>" + col1 + "</td><td>" + col2  
  34.      + "</td><td>" + col3 + "</td><td>" + col4  
  35.      + "</td></tr>");  
  36.   
  37.   }  
  38.   out.println("</table>");  
  39.   
  40.  } catch (ClassNotFoundException e) {  
  41.   e.printStackTrace();  
  42.  } catch (SQLException e) {  
  43.   e.printStackTrace();  
  44.  } finally {  
  45.   try {  
  46.    if (rs != null) {  
  47.     rs.close();  
  48.     rs = null;  
  49.    }  
  50.    if (stmt != null) {  
  51.     stmt.close();  
  52.     stmt = null;  
  53.    }  
  54.    if (conn != null) {  
  55.     conn.close();  
  56.     conn = null;  
  57.    }  
  58.   } catch (SQLException e) {  
  59.    e.printStackTrace();  
  60.   }  
  61.  }  
  62. %>  
  63.   
  64. </body>  
  65. </html>  

 

参考文献:tomcat与JAVAweb开发技术详解

猜你喜欢

转载自yingbin920.iteye.com/blog/1631485