1.导入驱动(放在lib下)
connector-java-5.0.8-bin.jar
2.导入配置文件(放在src下)
jdbc.properties
driverClass=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/数据库名称 user=用户名 password=密码
3.修改配置文件
4.导入工具类(放在utils包下)
JdbcUtils.java
package utils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ResourceBundle; public class JdbcUtils { static final String DRIVERCLASS; static final String URL; static final String USER; static final String PASSWORD; static { // 获取ResourceBundle ResourceBundle bundle = ResourceBundle.getBundle("jdbc"); // 获取指定的内容 DRIVERCLASS = bundle.getString("driverClass"); URL = bundle.getString("url"); USER = bundle.getString("user"); PASSWORD = bundle.getString("password"); } static { // 注册驱动 try { Class.forName(DRIVERCLASS); } catch (ClassNotFoundException e) { e.printStackTrace(); } } // 获取连接 public static Connection getConnection() throws SQLException { // 获取连接 return DriverManager.getConnection(URL, USER, PASSWORD); } /** * 释放资源 * * @param conn * 连接 * @param st * 语句执行者 * @param rs * 结果集 */ public static void closeResource(Connection conn, Statement st, ResultSet rs) { closeResultSet(rs); closeStatement(st); closeConn(conn); } /** * 释放连接 * * @param conn * 连接 */ public static void closeConn(Connection conn) { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } conn = null; } } /** * 释放语句执行者 * * @param st * 语句执行者 */ public static void closeStatement(Statement st) { if (st != null) { try { st.close(); } catch (SQLException e) { e.printStackTrace(); } st = null; } } /** * 释放结果集 * * @param rs * 结果集 */ public static void closeResultSet(ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } rs = null; } } }
5.在DAO层编写代码
Connection conn = null ; PreparedStatement st = null ; ResultSet rs = null ; try { //获取连接 conn = JdbcUtils.getConnection(); //编写sql String sql = "" ; //获取语句执行者 st = conn.prepareStatement(sql); //设置参数 //执行sql st.executeUpdate(); //处理结果 //rs = st.executeQuery() //int i = st.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); throw e; }finally{ JdbcUtils.closeResource(conn, st, rs); }
时间: 2024-11-05 13:44:44