码迷,mamicode.com
首页 > 数据库 > 详细

Tomcat下JDBC连接样例

时间:2017-03-28 19:39:01      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:auth   represent   java   test   out   except   ***   for   ring   

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8" import="java.sql.*"%>
 3 <!DOCTYPE html>
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>接收表单数据</title>
 8 </head>
 9 <body>
10 <p>获取文本框提交的信息:
11 <%
12 
13 
14 String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
15 String DB_URL = "jdbc:mysql://localhost:3306/first";
16 
17 
18 String USER = "root";
19 String PASS = "******";
20  
21 Connection conn = null;
22 Statement stmt = null;
23  try{
24     //load driver
25     Class.forName("com.mysql.jdbc.Driver");
26 
27     System.out.println("Connecting to database...");
28     //create connection
29     conn = DriverManager.getConnection(DB_URL,USER,PASS);
30 
31     System.out.println("Creating statement...");
32     //create query
33     stmt = conn.createStatement();
34     String sql;
35     sql = "SELECT * FROM first.author";
36     ResultSet rs = stmt.executeQuery(sql);
37     //get data
38     while(rs.next()){
39        int id  = rs.getInt("id");
40        int age = rs.getInt("age");
41        String author = rs.getString("author");
42        String represent = rs.getString("represent");
43 
44        System.out.print("ID: " + id);
45        System.out.print(", Age: " + age);
46        System.out.print(", Author: " + author);
47        System.out.println(", Represent: " + represent);
48     }
49     rs.close();
50     stmt.close();
51     conn.close();
52  }catch(SQLException se){
53     se.printStackTrace();
54  }catch(Exception e){
55     e.printStackTrace();
56  }finally{
57     try{
58        if(stmt!=null)
59           stmt.close();
60     }catch(SQLException se2){
61     }
62     try{
63        if(conn!=null)
64           conn.close();
65     }catch(SQLException se){
66        se.printStackTrace();
67     }
68  }
69  System.out.println("Goodbye!");
70 
71 %>
72 </body>
73 </html> 

 

Tomcat下JDBC连接样例

标签:auth   represent   java   test   out   except   ***   for   ring   

原文地址:http://www.cnblogs.com/duolk/p/6635997.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!