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();
                }
            }

        }
    }

  • 相关阅读:
    Delphi中 弹出框的用法
    VC++代码上传到VSS上 注意事项
    VC++ 屏蔽掉警告
    IIS LocalDB 登录失败
    SVN版本回滚实战
    Git常用命令图解
    C# 百度API地址坐标互相转换
    Quartz.NET浅谈一 : 简单Job使用(定时发送QQ邮件)
    发布自己的类库包到Nuget
    C# 常用日期取得
  • 原文地址:https://www.cnblogs.com/py1994/p/6008036.html
Copyright © 2011-2022 走看看