在java开发过程中,代码中时常用到一些scanner、random一样的类,他们是键盘录入,生成随机数的类,像一个工具一样,在java中被称为工具类。
2、步骤
封装jdbc工具类
加入获取数据库连接对象的方法
加入释放连接的方法
3、实例
package com.qianfeng.util; import java.sql.connection; import java.sql.drivermanager; import java.sql.resultset; import java.sql.sqlexception; import java.sql.statement; /** * jdbc工具类 * 有获取连接的方法 * @author dushine */ public class jdbcutil { /** * 获取数据库连接的方法 * @return connection conn * @throws sqlexception */ public static connection getconnection() throws sqlexception { string url = jdbc:mysql://localhost:3306/class?usessl=false; string user = root; string password = root; connection conn = drivermanager.getconnection(url,user,password); return conn; } /** * 释放连接的方法 * @param conn * @throws sqlexception */ public static void releasesourse(connection conn) throws sqlexception { if (conn != null) { conn.close(); } } /** * 释放连接的方法 * @param conn 数据库连接对象 * @param stmt 执行sql语句的对象 * @throws sqlexception */ public static void releasesourse(connection conn,statement stmt) throws sqlexception { if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } /** * 释放连接的方法 * @param conn 数据库连接对象 * @param stmt 执行sql语句的对象 * @param resultset 执行sql语句的返回的结果集 * @throws sqlexception */ public static void releasesourse(connection conn,statement stmt,resultset resultset) throws sqlexception { if (resultset != null) { resultset.close(); } if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } }
以上就是如何在java中封装jdbc工具类?的详细内容。