赞
踩
1、添加maven依赖
- <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>8.0.29</version>
- </dependency>
2、单处理:更新、删除、插入
- public int singleOperate(String sql, Map<Integer, String> map) throws ClassNotFoundException, SQLException {
- Class.forName("com.mysql.cj.jdbc.Driver");
- Connection conn = DriverManager.getConnection(sql_host, sql_user, sql_password);
- PreparedStatement ps = conn.prepareStatement(sql);
- for (Map.Entry<Integer, String> entry : map.entrySet()) {
- ps.setString(entry.getKey(), entry.getValue());
- }
- int i = ps.executeUpdate();
- ps.close();
- conn.close();
- return i;
- }
3、批处理:更新、删除、插入
- public String batchOperate(String sql, List<Map<Integer, String>> list) throws ClassNotFoundException, SQLException {
- Class.forName("com.mysql.cj.jdbc.Driver");
- Connection conn = DriverManager.getConnection(sql_host, sql_user, sql_password);
- PreparedStatement ps = conn.prepareStatement(sql);
- for (Map<Integer, String> map : list) {
- for (Map.Entry<Integer, String> entry : map.entrySet()) {
- ps.setString(entry.getKey(), entry.getValue());
- }
- ps.addBatch();//添加到同一个批处理中
- }
- String str_re = Arrays.toString(ps.executeBatch());
- ps.close();
- conn.close();
- return str_re;
- }
4、查询
- public ResultSet query(String sql) throws ClassNotFoundException, SQLException {
- Class.forName("com.mysql.cj.jdbc.Driver");
- Connection conn = DriverManager.getConnection(sql_host, sql_user, sql_password);
- Statement stmt = conn.createStatement();
- return stmt.executeQuery(sql);
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。