• 构建JDBC的基本代码


    import java.sql.*;
    public class Test {
        public static void main(String[] args) {
             Connection con = null;
             Statement sta = null;
             ResultSet res = null;
             try {
    /*                     <!--加载驱动类-->                                    */        
                 Class.forName("com.mysql.jdbc.Driver");   
                 String url = "jdbc:mysql://localhost:3306/test";
                 String user = "root";
                 String passwd = "root";
    /*         <!--通过大管家拿到与指定数据库连接的接口Connection的一个对象-->        */    
                 con = DriverManager.getConnection(url,user,passwd);                 //ClassNotFoundException
    /*         <!--通过接口con中的特定方法拿到sql语句对象-->        */        
                 String sql = "select * from login";
                 sta = con.createStatement();
    /*         <!--将结果集返回给ResultSet对象-->        */                
                 res = sta.executeQuery(sql);
                 while(res.next()){
                     System.out.println(res.getString("username"));     //username 为数据库里面的字段名
                 }    
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }catch(SQLException e){
                e.printStackTrace();
            }finally{
                try{
                    if(res!=null){    <!--finally 后面的代码是一定会执行的,用finally的好处就是当在增删改查阶段产生了异常,导致程序无法往下走,那么你

                   建立的 con、res、sta连接就无法关闭了,那么当你的程序启动多次以后,你的内存就会不知不觉的被全部占用了。

                   这时候finally的特点就是,无论try还是catch里面产生什么样的异常都会义无反顾走finally,从而内存不会被浪费-->

             res.close();
                        res = null;        //关闭之后将空间回收
                    }
                    if(sta!=null){
                        sta.close();
                        sta = null;
                    }
                    if(con!=null){
                        con.close();
                        con = null;
                    }
                }catch(SQLException e){
                    e.printStackTrace();
                }
            }

        }
    }

  • 相关阅读:
    MINA简单的介绍
    java classloader详解
    nginx 和 tomcat 组合搭建后端负载均衡
    nginx主要配置
    Mysql知识汇总笔记
    gradle 构建java工程
    决策树
    如何使用hadoop RPC机制
    PowerPoint插入公式快捷键
    C++基础
  • 原文地址:https://www.cnblogs.com/py1994/p/6008036.html
Copyright © 2020-2023  润新知