通过JDBC API访问数据库的jsp范例
jsp中使用jdbc api 访问数据库
1 <%@ page language="java" contentType="text/html; charset=utf-8" 2 pageEncoding="utf-8"%> 3 <%@ page import="java.io.*" %> 4 <%@ page import="java.util.*" %> 5 <%@ page import="java.sql.*" %> 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=utf-8"> 10 <title>TestJDBCAPI</title> 11 </head> 12 <body> 13 <% 14 try{ 15 Connection con; 16 Statement stmt; 17 ResultSet rs; 18 19 //Mysql被Load 20 Class.forName("com.mysql.jdbc.Driver"); 21 //注册mysql(要有MySQL的jar包) 22 DriverManager.registerDriver(new com.mysql.jdbc.Driver()); 23 //用适当的Driver connect to DB 24 String dburl = "jdbc:mysql://localhost:3306/BookDB?useUnicode=true&characterEncoding=utf-8"; 25 String dbuser = "username"; 26 String dbpwd = "password"; 27 28 //Create db's connection 29 con = java.sql.DriverManager.getConnection(dburl,dbuser,dbpwd); 30 //Create SQL 申明 31 stmt = con.createStatement(); 32 //add data 33 stmt.executeUpdate("插入具体的insert语句"); 34 35 //select data 36 rs = stmt.executeQuery("select 语句"); 37 38 //Out select result 39 out.println("<table border=1 width=400>"); 40 while(rs.next()){ 41 String col1 = rs.getString(1); 42 String col2 = rs.getString(2); 43 String col3 = rs.getString(3); 44 float col4 = rs.getFloat(4); 45 46 //Print datas 47 out.println("<tr><td>"+col1+"</td>" 48 +"<td>"+col2+"</td>" 49 +"<td>"+col3+"</td>" 50 +"<td>"+col4+"</td></tr>"); 51 } 52 out.println("</table>"); 53 54 //Delete datas 55 stmt.executeUpdate("Delete 语句"); 56 57 //CLose 58 rs.close(); 59 stmt.close(); 60 con.close(); 61 62 }catch(Exception e){ 63 out.println(e.getMessage()); 64 } 65 %> 66 </body> 67 </html>