通過JDBC API訪問資料庫的jsp範例

來源:互聯網
上載者:User
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>

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.