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被Load20 Class.forName("com.mysql.jdbc.Driver");21 //註冊mysql(要有MySQL的jar包)22 DriverManager.registerDriver(new com.mysql.jdbc.Driver());23 //用適當的Driver connect to DB24 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 connection29 con = java.sql.DriverManager.getConnection(dburl,dbuser,dbpwd);30 //Create SQL 申明31 stmt = con.createStatement();32 //add data33 stmt.executeUpdate("插入具體的insert語句");34 35 //select data36 rs = stmt.executeQuery("select 語句");37 38 //Out select result39 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 datas47 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 datas55 stmt.executeUpdate("Delete 語句");56 57 //CLose58 rs.close();59 stmt.close();60 con.close();61 62 }catch(Exception e){63 out.println(e.getMessage());64 }65 %>66 </body>67 </html>