Get the App
SLTechnology News&Howtos  ›  Database  › 

JDBC series: (2.5) create JDBCUtils tool classes

Shulou Source: shulou.com Published: 2022-06-01 15:37:18 10月14日 Update

1. Create the db.properties file url=jdbc:mysql://localhost:3306/testdbuser=rootpassword=rootdriverClass=com.mysql.jdbc.Driver

2. JDBC tool class: JDBCUtil.javapackage com.rk.db.utils;import java.io.IOException;import java.io.InputStream;import java.util.Properties;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;/** * JDBC tool class * @ author RK * * / public class JDBCUtil {private static final String url; private static final String user; private static final String password Private static final String driverClass / * static code block (loaded only once) * / static {try {/ / read the db.properties file InputStream inStream = JDBCUtil.class.getClassLoader () .getResourceAsStream ("db.properties") Properties props = new Properties (); / / load file props.load (inStream); / / read information url = props.getProperty ("url") User = props.getProperty ("user"); password = props.getProperty ("password"); driverClass = props.getProperty ("driverClass"); / / register driver Class.forName (driverClass) } catch (IOException e) {System.out.println ("error reading database configuration file"); throw new RuntimeException (e) } catch (ClassNotFoundException e) {System.out.println ("database driver registration error"); throw new RuntimeException (e) }} / * get the database connection * @ return database connection * / public static Connection getConnection () {try {return DriverManager.getConnection (url,user,password) } catch (SQLException e) {System.out.println ("error getting database connection"); throw new RuntimeException (e) }} / * close Connection, Statement, and ResultSet * @ param conn database connections * @ param stmt commands for executing SQL statements * @ param rs result sets * / public static void close (Connection conn,Statement stmt ResultSet rs) {closeQuietly (rs) CloseQuietly (stmt); closeQuietly (conn) } / * quietly shut down database resources * @ param ac implements the object of the AutoCloseable interface * / public static void closeQuietly (AutoCloseable ac) {if (ac! = null) {try {ac.close () } catch (Exception e) {e.printStackTrace ();}}

Tags: Data database file tool program quiet code information command object interface result statement resource static driver configuration driver Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Shulou Technology Microsoft Linux vpn