JDBC编写通用增删改查

public class test {
    String url = "jdbc:mysql://localhost:3306/mytest?serverTimezone=UTC&characterEncoding=utf-8";
    String user = "root";
    String password = "root";
    String driver = "com.mysql.jdbc.Driver";
    String insert_sql = "insert into user(id,name) values(?,?)";
    String select_sql = "select id,name from user WHERE id=? and name=?";
    @Test
    public void test(){
        parameterMetaData(insert_sql,new Object[]{"1","tom"});
        List users = resultSetMetaData(select_sql, new Object[]{"1", "tom"}, User.class);
        for (User user:users) {
            System.out.println(user.toString());
        }
    }
    //参数元数据编写增删改通用方法
    public void parameterMetaData(String sql,Object[] params){
        try {
            //获取数据库连接
            Class.forName(driver);
            Connection connection = DriverManager.getConnection(url, user, password);
            //获取PreparedStatement对象
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            //获取ParameterMetaData参数元数据
            ParameterMetaData parameterMetaData = preparedStatement.getParameterMetaData();
            //获取sql参数的数量
            int parameterCount = parameterMetaData.getParameterCount();
            //给参数赋值
            for(int i=0;i List resultSetMetaData(String sql, Object[] params, Class clazz){
        //创建List保存要查询的数据
        List list = new ArrayList<>();
        try {
            //获取数据库连接
            Class.forName(driver);
            Connection connection = DriverManager.getConnection(url, user, password);
            //获取PreparedStatement对象
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            //获取ParameterMetaData参数元数据
            ParameterMetaData parameterMetaData = preparedStatement.getParameterMetaData();
            //获取sql参数的数量
            int parameterCount = parameterMetaData.getParameterCount();
            //给参数赋值
            for(int i=0;i

 

你可能感兴趣的:(JDBC编写通用增删改查)