封装非DQL语句 DaseDao类配合JdbcUtilsV2类,使用 BaseDao类完成了 4.创建statement 5.占位符赋值6.发SQL语句7.结果解析 JdbcUtilsV2类完成1.注册驱动 2.获取连接 8.回收资源,只需要在外3.编写SQL语句即可。
package com.shayiheng.api.utils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Objects;
public abstract class BaseDao {
public int executeUpdate(String sql, Object... params) throws SQLException {
Connection connection = JdbcUtilsV2.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(sql);
for (int i = 1; i <= params.length; i++) {
preparedStatement.setObject(i,params[i-1]);
}
int rows=preparedStatement.executeUpdate();
preparedStatement.close();
if (connection.getAutoCommit()){
JdbcUtilsV2.freeConnection();
}
return rows;
}
}
package com.shayiheng.api.utils;
import org.junit.Test;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PSCURDPart extends BaseDao {
@Test
public void testInsert() throws ClassNotFoundException, SQLException {
String sql = "INSERT INTO t_user(account, PASSWORD,nickname)VALUES(?,?,?);";
int row= executeUpdate(sql,"test123","21700411","tom");
System.out.println("row=" + row);
}
@Test
public void testUpdate() throws SQLException, ClassNotFoundException {
String sql = "UPDATE t_user SET account=?,PASSWORD=?,nickname=?WHERE id=?;";
int row= executeUpdate(sql,"admins","3333","ergouzi",2 );
System.out.println(("row=" + row));
}
@Test
public void testDelete() throws SQLException, ClassNotFoundException {
String sql = "DELETE FROM t_user WHERE id=?;";
int row = executeUpdate(sql,"80021");
System.out.println(("row=" + row));
}
}