经常看到有人问JSP关于访问数据库的问题
JSP访问数据库的方法其实和servelet访问数据库一样,只是有一些语法上的区别
通常在访问数据库时要注意以下几点:
1.数据库安装时编码应该设置为gb2312避免遇到汉字变成?的问题
2.jsp页面字符编码设置 charset=gb2312 防止页面显示汉字为乱码
3.注意out.printn()输出是否正确。
- <%@ page language="java" contentType="text/html; charset=gb2312"
- pageEncoding="gb2312"%>
- <%@ page import="java.io.*"%>
- <%@ page import="java.sql.*"%>
- <%@ page import="java.util.*"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
- <title>DBACCESS</title>
- </head>
- <body>
- <%
- ResultSet rs = null;
- Statement stmt = null;
- Connection conn = null;
- try {
- Class.forName("com.mysql.jdbc.Driver");
- String url = "jdbc:mysql://localhost/BookDB?";
- String user = "root";
- String pw = "123456";
- conn = DriverManager.getConnection(url, user, pw);
- stmt = conn.createStatement();
- //stmt.executeUpdate("insert into BOOKS values('999','TOM''TomCAT',44,5,'TOMCAT1',80000)");
- rs = stmt.executeQuery("select ID,NAME,TITLE,PRICE from BOOKS");
- out.println("<table border=1 width=400>");
- while (rs.next()) {
- String col1 = rs.getString(1);
- String col2 = rs.getString(2);
- String col3 = rs.getString(3);
- float col4 = rs.getFloat(4);
- out.println("<tr><td>" + col1 + "</td><td>" + col2
- + "</td><td>" + col3 + "</td><td>" + col4
- + "</td></tr>");
- }
- out.println("</table>");
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- try {
- if (rs != null) {
- rs.close();
- rs = null;
- }
- if (stmt != null) {
- stmt.close();
- stmt = null;
- }
- if (conn != null) {
- conn.close();
- conn = null;
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- %>
- </body>
- </html>
参考文献:tomcat与JAVAweb开发技术详解