JDBC编程自动关闭的两种方式

方式一:通过try-catch-finally进行关闭,利用finally必须执行的特性

例如:

import java.sql.*;
public class WriteData {
    public static void main(String[] args) {
        Connection connection= null;
        Statement statement=null;
        ResultSet effect=null;
        //1.
        try {
            Class.forName ( " com.mysql.jdbc.Driver" );
            //2.JDBC url 协议
            String url="jdbc:mysql://127.0.0.1:3306/memo?user=root&password=wzp961208";
                connection = DriverManager.getConnection ( url );
            //3.创建命令
           statement=connection.createStatement ();
            //4.写入
            String sql="insert into memo_group(name,created_time) values ('今天是个好日子','2019-06-24 19:42:00');";
            //5执行
             effect=statement.executeQuery (sql  );
            //6.
            System.out.println (effect );

        } catch (ClassNotFoundException e) {
            e.printStackTrace ( );
        } catch (SQLException e) {
            e.printStackTrace ( );
        }finally {
            //7.关闭结果集
            try {
                if(effect!=null) {
                    effect.close ( );
                }
                //8.关闭命令
                if(statement!=null) {
                    statement.close ( );
                }
                //9.关闭连接
                if(connection!=null) {
                    connection.close ( );
                }
            } catch (SQLException e) {
                e.printStackTrace ( );
            }
        }
    }
}

二、运用自动关闭方式

例如:

import java.sql.*;
public class 自动关闭 {
    public static void main(String[] args) {
        try {
            Class.forName ( "com.mysql.jdbc.Driver" );
            String url="jdbc:mysql://127.0.0.1:3306/memo?user=root&password=wzp961208";
            String sql="select id ,name,created_time,modify_time from memo_group";
            try(Connection connection=DriverManager.getConnection ( url ); Statement statement=connection.createStatement ();
                ResultSet resultSet=statement.executeQuery ( sql )){
                while(resultSet.next()){
                    int id=resultSet.getInt ( "id" );
                    String name=resultSet.getString ( "name" );
                    Timestamp createTime=resultSet.getTimestamp ( "created_time" );
                    Timestamp modifyTime=resultSet.getTimestamp ( "modify_time" );
                    System.out.println (id+" "+name+" "+createTime+" "+modifyTime+" " );
                }

            }catch  (SQLException e) {
                e.printStackTrace ( );
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace ( );
        }
    }
}
发布了129 篇原创文章 · 获赞 4 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/beststudent_/article/details/95813293