当前位置:   article > 正文

用mysql-connector-java操作数据库(JDBC)_mysql-connector-java maven response

mysql-connector-java maven response

1、添加maven依赖

  1. <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
  2. <dependency>
  3. <groupId>mysql</groupId>
  4. <artifactId>mysql-connector-java</artifactId>
  5. <version>8.0.29</version>
  6. </dependency>

2、单处理:更新、删除、插入

  1. public int singleOperate(String sql, Map<Integer, String> map) throws ClassNotFoundException, SQLException {
  2. Class.forName("com.mysql.cj.jdbc.Driver");
  3. Connection conn = DriverManager.getConnection(sql_host, sql_user, sql_password);
  4. PreparedStatement ps = conn.prepareStatement(sql);
  5. for (Map.Entry<Integer, String> entry : map.entrySet()) {
  6. ps.setString(entry.getKey(), entry.getValue());
  7. }
  8. int i = ps.executeUpdate();
  9. ps.close();
  10. conn.close();
  11. return i;
  12. }

3、批处理:更新、删除、插入

  1. public String batchOperate(String sql, List<Map<Integer, String>> list) throws ClassNotFoundException, SQLException {
  2. Class.forName("com.mysql.cj.jdbc.Driver");
  3. Connection conn = DriverManager.getConnection(sql_host, sql_user, sql_password);
  4. PreparedStatement ps = conn.prepareStatement(sql);
  5. for (Map<Integer, String> map : list) {
  6. for (Map.Entry<Integer, String> entry : map.entrySet()) {
  7. ps.setString(entry.getKey(), entry.getValue());
  8. }
  9. ps.addBatch();//添加到同一个批处理中
  10. }
  11. String str_re = Arrays.toString(ps.executeBatch());
  12. ps.close();
  13. conn.close();
  14. return str_re;
  15. }

4、查询

  1. public ResultSet query(String sql) throws ClassNotFoundException, SQLException {
  2. Class.forName("com.mysql.cj.jdbc.Driver");
  3. Connection conn = DriverManager.getConnection(sql_host, sql_user, sql_password);
  4. Statement stmt = conn.createStatement();
  5. return stmt.executeQuery(sql);
  6. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/513931
推荐阅读
相关标签
  

闽ICP备14008679号