mysql ----BaseDao工具类
Posted gun-a
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mysql ----BaseDao工具类相关的知识,希望对你有一定的参考价值。
package com.zjw.dao; import java.sql.*; /** * 工具类 */ public class BaseDao { static final String DB_URL = "jdbc:mysql://localhost:3306/数据库"; static final String username = "用户名"; static final String paw = "密码"; protected Connection conn; protected ResultSet rs; protected PreparedStatement ps; /** * 数据库的连接 * * @return */ public void connect() { try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(DB_URL, username, paw); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } /** * 增删改 */ public int executeUpdate(String sql, Object... obj) { int row = 0; try { connect(); ps = conn.prepareStatement(sql); if (obj != null) { for (int i = 0; i < obj.length; i++) { ps.setObject(i + 1, obj[i]); } row = ps.executeUpdate(); } close(conn, null, rs); } catch (SQLException e) { e.printStackTrace(); } return row; } /** * 查询数据 * * @param sql * @param obj * @return */ public void executeQuery(String sql, Object... obj) { try { connect(); ps = conn.prepareStatement(sql); if (obj != null) { for (int i = 0; i < obj.length; i++) { ps.setObject(i + 1, obj[i]); } } rs = ps.executeQuery(); } catch (SQLException e) { e.printStackTrace(); } } /** * 关闭流 * * @param conn * @param ps * @param rs */ public void close(Connection conn, PreparedStatement ps, ResultSet rs) { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
以上是关于mysql ----BaseDao工具类的主要内容,如果未能解决你的问题,请参考以下文章