您当前的位置: 首页 > 

梁云亮

暂无认证

  • 1浏览

    0关注

    1211博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

2:Jdbc工具类

梁云亮 发布时间:2021-11-01 10:42:14 ,浏览量:1

工具类
public final class JdbcUtil {
    /**
     * 连接字符串
     */
    private static final String URL = "jdbc:mysql://localhost:3306/db_test?useSSL=false&serverTimezone=GMT%2B8&characterEncoding=utf8&useUnicode=true";
    /**
     * 用户名
     */
    private static final String USERNAME = "root";
    /**
     * 密码
     */
    private static final String PASSWORD = "root";
    /**
     * 驱动类名
     */
    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";

    static {
        try {
            // 1、加载驱动
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL, USERNAME, PASSWORD);
    }

    public static void release(ResultSet rs, Statement stmt, Connection conn) {
        // 建议采用这种形式来释放资源,因为finally里面的一定会被释放
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                if (conn != null) {
                    try {
                        conn.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
测试代码
public final class JdbcUtilTest {
	private static void selectAllDepts(String sql) {
		try {
			// 2、建立连接
			Connection conn = JdbcUtil.getConnection();
			// 3、获取Statement对象
			Statement stmt = conn.createStatement();
			// 执行SQL语句
			ResultSet rs = stmt.executeQuery(sql);
			// 处理返回的结果
			while (rs.next()) {
				System.out.println(rs.getInt(1) + "  " + rs.getString("dname") + "  "+ rs.getString("loc"));
			}
			// 释放资源
			JdbcUtil.release(rs, stmt, conn);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		String sql = "SELECT * FROM tb_dept";
		selectAllDepts(sql);
	}
}

代码优化

将数据库的连接信息写到属性配置文件中

  • 属性配置文件:mysql.properties

    url=jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=GMT%2B8&characterEncoding=utf8&useUnicode=true
    user=root
    password=root
    
  • 工具类

public class JdbcUtil {
    private static String url;
    private static String user;
    private static String password;

    static {
        //Map的實現類
        Properties properties = new Properties();
        // 重点
        InputStream rss = JdbcUtil.class.getResourceAsStream("/mysql.properties");
        try {
            //加載驅動(Java項目可以不要改句,web項目必須)
            Class.forName("com.mysql.jdbc.Driver");
            //加載properties文件
            properties.load(rss);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        url = properties.getProperty("url");
        System.out.println(url);
        user = properties.getProperty("user");
        password = properties.getProperty("password");
    }

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

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

为了提高程序的性能,建议采用数据库连接池技术,请参看博客:数据库连接池技术

关注
打赏
1665409997
查看更多评论
立即登录/注册

微信扫码登录

0.0402s