JAVA JDBC usage tutorial

Preface

Here directly write the connection and release resources in jdbc into the util package to facilitate subsequent use.

Code display and explanation

Overall display of tool JDBCUtils

public class JDBCUtils {
    
    
    private static String url;
    private static String user;
    private static String password;
    private static String driver;
    /**
     *
     * @Description: 使用静态代码块读取 配置文件中的内容
     * 这样只要读取一次就可以了
     *
     * @auther: FARO_Z
     * @date: 2:16 上午 2020/7/19
     * @param:
     * @return:
     *
     */
    static {
    
    
        //1.创建Properties集合类
        Properties pro=new Properties();
        //2.加载文件
        try {
    
    
            /*
              pro.load(new FileReader(path));中的path换成直接写src/jdbc.properties 可能会出现读不出来的情况
              所以要通过下面的方式动态获取配置文件的路径

              注意:使用下面这种方式,路径中一定不能有中文出现
                路径必须全部都是英文
             */

//            ClassLoader classloader=JDBCUtils.class.getClassLoader();
//            URL resource =classloader.getResource("jdbc.properties");
//            String path=resource.getPath();
//            System.out.println(path);
//            pro.load(new FileReader(path));
            pro.load(new FileReader("src/jdbc.properties"));
            //3.获取数据
            url=pro.getProperty("url");
            user=pro.getProperty("user");
            password=pro.getProperty("password");
            driver=pro.getProperty("driver");
            Class.forName(driver);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
    
    
            e.printStackTrace();
        }
    }

    /**
     *
     * @Description: 获取链接
     *
     * @auther: FARO_Z
     * @date: 2:04 上午 2020/7/19
     * @param: []
     * @return: java.sql.Connection
     *
     */
    public static Connection getConnection() throws SQLException {
    
    
        return DriverManager.getConnection(url,user,password);
    }

    /**
     *
     * @Description: 释放资源,这是第一个重载
     *
     * @auther: FARO_Z
     * @date: 2:06 上午 2020/7/19
     * @param: [stmt, conn]
     * @return: void
     *
     */
    public static void close(Statement stmt,Connection conn) {
    
    
        if (stmt!=null) {
    
    
            try {
    
    
                stmt.close();
            } catch (SQLException throwables) {
    
    
                throwables.printStackTrace();
            }
        }

        if (conn!=null) {
    
    
            try {
    
    
                conn.close();
            } catch (SQLException throwables) {
    
    
                throwables.printStackTrace();
            }
        }
    }

    /**
     *
     * @Description: 释放资源,第二个重载
     *
     * @auther: FARO_Z
     * @date: 2:07 上午 2020/7/19
     * @param: [rs, stmt, conn]
     * @return: void
     *
     */
    public static void close(ResultSet rs,Statement stmt, Connection conn) {
    
    
        if (stmt!=null) {
    
    
            try {
    
    
                stmt.close();
            } catch (SQLException throwables) {
    
    
                throwables.printStackTrace();
            }
        }

        if (conn!=null) {
    
    
            try {
    
    
                conn.close();
            } catch (SQLException throwables) {
    
    
                throwables.printStackTrace();
            }
        }

        if (rs!=null) {
    
    
            try {
    
    
                rs.close();
            } catch (SQLException throwables) {
    
    
                throwables.printStackTrace();
            }
        }
    }
}

Detailed method


Static code block

Here, the url, uesr, and password
configuration files are stored in the src directory
through the configuration file, and the corresponding key value in the configuration file is obtained through the Properties collection.
Insert picture description here
Insert picture description here

static {
    
    
        //1.创建Properties集合类
        Properties pro=new Properties();
        //2.加载文件
        try {
    
    
            /*
              pro.load(new FileReader(path));中的path换成直接写src/jdbc.properties 可能会出现读不出来的情况
              所以要通过下面的方式动态获取配置文件的路径

              注意:使用下面这种方式,路径中一定不能有中文出现
                路径必须全部都是英文
             */

//            ClassLoader classloader=JDBCUtils.class.getClassLoader();
//            URL resource =classloader.getResource("jdbc.properties");
//            String path=resource.getPath();
//            System.out.println(path);
//            pro.load(new FileReader(path));

			//获取配置文件中的值
            pro.load(new FileReader("src/jdbc.properties"));
            //3.获取数据
            url=pro.getProperty("url");
            user=pro.getProperty("user");
            password=pro.getProperty("password");
            driver=pro.getProperty("driver");
            Class.forName(driver);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
    
    
            e.printStackTrace();
        }
    }


getConnection

Here, after obtaining the url, user, and password in the configuration file, directly call DriverManager in JDBC to get the connection and return

 public static Connection getConnection() throws SQLException {
    
    
        return DriverManager.getConnection(url,user,password);
    }

close()

There are two close() methods, one without ResultSet parameters, and one with parameters.
This is because when the query operation is performed,
the result is queried or stored in
the ResultSet. After the ResultSet is used, its resources must be released.

 public static void close(ResultSet rs,Statement stmt, Connection conn) {
    
    
        if (stmt!=null) {
    
    
            try {
    
    
                stmt.close();
            } catch (SQLException throwables) {
    
    
                throwables.printStackTrace();
            }
        }

        if (conn!=null) {
    
    
            try {
    
    
                conn.close();
            } catch (SQLException throwables) {
    
    
                throwables.printStackTrace();
            }
        }

        if (rs!=null) {
    
    
            try {
    
    
                rs.close();
            } catch (SQLException throwables) {
    
    
                throwables.printStackTrace();
            }
        }
    }

Use test

Here we store the data in the following table into ArrayList and output
Insert picture description here

public class JDBCDemo8 {
    
    
    public static void main(String[] args) {
    
    
        Connection conn=null;
        Statement stmt=null;
        ResultSet rs=null;
        String sql="select * from account";
        ArrayList<Account> list=new ArrayList<Account>();
        try {
    
    
            conn=JDBCUtils.getConnection();//获取数据库连接
            stmt=conn.createStatement();//获取执行对象
            rs=stmt.executeQuery(sql);//执行查找
            while (rs.next()) {
    
    
                //三个参数分别是:             id          name          balance
                list.add(new Account(rs.getInt(1),rs.getString(2),rs.getInt(3)));
            }
        } catch (SQLException throwables) {
    
    
            throwables.printStackTrace();
        } finally {
    
    
            JDBCUtils.close(rs,stmt,conn);//释放资源
        }
        ArrayListUtil.outputArrayList(list);//打印结果
    }
}

The final result is as shown below
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44062380/article/details/107446094