• Tomcat下JDBC连接样例


     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> 
  • 相关阅读:
    Java实现 LeetCode 56 合并区间
    JQuery实现对html结点的操作(创建,添加,删除)
    JQuery实现对html结点的操作(创建,添加,删除)
    JQuery实现对html结点的操作(创建,添加,删除)
    Java实现 LeetCode 55 跳跃游戏
    Java实现 LeetCode 55 跳跃游戏
    Java实现 LeetCode 55 跳跃游戏
    Java实现 LeetCode 54 螺旋矩阵
    Java实现 LeetCode 54 螺旋矩阵
    Java实现 LeetCode 54 螺旋矩阵
  • 原文地址:https://www.cnblogs.com/duolk/p/6635997.html
Copyright © 2020-2023  润新知