zoukankan      html  css  js  c++  java
  • JDBC 工具类

    在Java编程过程中 我们需要连接数据库 所以数据库的连接和增删改查操作是非常基本的操作同时又非常的重要。同时在JDBC编程中 ,有很多的方法如更新个查找操作,我们可以对其进行封装,
    提高我们编码的效率。
    本文将数据的连接方法,数据查找的有参数查找 和无参数查找,更新操作的方法进行具体展现。我们可以在我们项目直接新建
    DBHelper类,并将代码拷贝到自己的类中导入相应的包便可以直接使用





    public
    class DBHelper { //dbName 当前项目使用的数据库名称 username 数据库的用户名 password 数据库的密码 private static String url = "jdbc:mysql://localhost:3306/"; private static String dbName = "******"; private static String username = "****"; private static String password = "****"; //该方法用于链接数据库 public static Connection getConnection() { Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(url + dbName, username, password); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return conn; } //该方法用于没有参数的查询 public static List<Map<String, Object>> executeQuery(String sql) { return executeQuery(sql, new String[0]); } //该方法用于含有参数的查询 参数个数为可变 public static List<Map<String, Object>> executeQuery(String sql, Object...param) { Connection conn = null; PreparedStatement pst = null; ResultSet rs = null; List<Map<String, Object>> resut = new ArrayList<>(); Map<String, Object> map = null; try{ conn = getConnection(); pst = conn.prepareStatement(sql); for (int i = 0; i < param.length; i++) { pst.setObject(i+1, param[i]); } rs = pst.executeQuery(); ResultSetMetaData rsm = rs.getMetaData(); String[] columns = new String[rsm.getColumnCount()]; for (int i = 0; i < rsm.getColumnCount(); i++) { columns[i] = rsm.getColumnName(i + 1); } rs.beforeFirst(); while(rs.next()) { map = new HashMap<>(); for(String col : columns) { map.put(col, rs.getObject(col)); } resut.add(map); } rs.close(); pst.close(); conn.close(); } catch (SQLException ex) { ex.printStackTrace(); } return resut; } //该方法用于更新操作 public static int executeUpdate(String sql, Object[] param) { Connection conn = null; PreparedStatement pst = null; int result = 0; try { conn = getConnection(); pst = conn.prepareStatement(sql); for (int i = 0; i < param.length; i++) { pst.setObject(i + 1, param[i]); } result = pst.executeUpdate(); pst.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } return result; } }
  • 相关阅读:
    HTTP协议详解
    【VC++开发实战】迅雷晒密及批量查询流量程序
    C/C++中指针和引用之相关问题研究
    C++类中拷贝构造函数详解
    构造函数为什么不能是虚函数
    High一下!
    文件搜索神器everything 你不知道的技巧总结
    不要被C++“自动生成”所蒙骗
    对象的传值与返回
    深入浅出Node.js (3)
  • 原文地址:https://www.cnblogs.com/huangzhimin/p/6134490.html
Copyright © 2011-2022 走看看