zoukankan      html  css  js  c++  java
  • JDBC 04: 创建JDBCUtils并重构之前的代码

    1. 创建JDBCUtils

    package com.Jasper2003.jdbc01;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class JDBCUtils {
    
        private static final String connectionURL = "jdbc:mysql://localhost:3306/web01?useUnicode=true&characterEncoding=UTF8&useSSL=false";
        private static final String username = "root";
        private static final String password = "root";
        
        public static Connection getConnection() {
            try {
                Class.forName("com.mysql.jdbc.Driver");
                return DriverManager.getConnection(connectionURL,username,password);
            }catch(Exception e) {
                e.printStackTrace();
            }
            
            return null;
        }
        
        public static void close(ResultSet rs, Statement stmt, Connection con) {
            try {
                if(rs!=null)
                    rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        
            try {
                if(stmt!=null)
                    stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        
            try {
                if(con!=null)
                    con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    2. 重构selectAll()

    public static void selectAll() {
    
            
            Connection con = null;
            Statement stmt = null;
            ResultSet rs = null;
            
            try {
                con = JDBCUtils.getConnection();
                stmt = con.createStatement();
                rs = stmt.executeQuery("select * from user");
                
                while(rs.next()) {
    
              System.out.println(rs.getInt("id")+","+rs.getString("username")+","+rs.getString("password"));
                }    
                
            } catch (Exception e) {
                
                e.printStackTrace();
            } finally {
                JDBCUtils.close(rs, stmt, con);
            }
        }
  • 相关阅读:
    H3C S3600-28TP-SI配置命令
    笔记本双网卡内外同上
    计算机存储单位与宽带单位
    linux 设置网卡
    linux 挂载命令详解
    vue实现京东动态楼层效果
    js字符与ASCII码互转的方法
    UartAssist串口调试工具
    高字节和低字节是什么意思?
    int16, int32, int64等类型说明
  • 原文地址:https://www.cnblogs.com/JasperZhao/p/13539484.html
Copyright © 2011-2022 走看看