zoukankan      html  css  js  c++  java
  • 构建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();
                }
            }

        }
    }

  • 相关阅读:
    [Powershell]导出指定的定时计划任务
    [Powershell]发布基于.NET Framework的WebAPI和Job控制台程序项目
    [Powershell]使用Msbuild构建基于.NET Framework的WebAPI项目
    [最新].NET Core ORM 开源项目一览,持续更新
    【最新】Xmanager Power Suite 6.0 Build 0017
    Git抽取版本之间的差异,打包解压
    PuppeteerSharp+AngleSharp的爬虫实战之汽车之家数据抓取
    PostgreSql之在group by查询下拼接列字符串
    同事问如何判断同花顺,我用javascript的二维数组写了个简易demo
    Gitlab定义安全变量遇到无法转义的字符——感叹号
  • 原文地址:https://www.cnblogs.com/py1994/p/6008036.html
Copyright © 2011-2022 走看看