CRUD增删改查,封装执行sql的方法
package day05.jdbc;
/*
crud 增删改查
*/
import com.google.common.collect.Lists;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
public class Demo05 {
public static void main(String[] args) throws Exception{
delete();
//update();
// insert();
//query();
}
public static void delete(){
String sql ="delete from auth_group where id =?";
ex_sql(sql, Lists.newArrayList(1));
}
public static int ex_sql(String sql, List<Object> params){
try(Connection conn = MysqlUtil.getConn();) {
PreparedStatement ps = conn.prepareStatement(sql);
for (int i =0;i<params.size();i++){
// 这里是i+1,不是i,因为jdbc是从1开始数的
ps.setObject(i+1,params.get(i));}
int n = ps.executeUpdate();
return n;
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
public static void query() throws Exception{
Connection conn = MysqlUtil.getConn();
String sql ="select * from auth_group";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet resultSet = ps.executeQuery();
while (resultSet.next()){
long id = resultSet.getLong(1);
String name = resultSet.getString(2);
System.out.println(String.format("id:%d,name:%s", id, name));
}
MysqlUtil.close(conn);
}
public static void insert() throws Exception{
Connection conn = MysqlUtil.getConn();
String sql ="insert into auth_group values(?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setLong(1,1);
ps.setString(2,"miaojiang");
// 除了查询用executeQuery(),其他的增删改用executeUpdate()
// 这里得到的int n是影响了多少行数据
int n = ps.executeUpdate();
System.out.println("n = " + n);
MysqlUtil.close(conn);}
public static void update() throws Exception{
Connection conn = MysqlUtil.getConn();
String sql ="update auth_group set name=? where id =?";
PreparedStatement ps = conn.prepareStatement(sql);
// parameterIndex代表?的下标
ps.setString(1,"shuai");
ps.setLong(2,1);
// 除了查询用executeQuery(),其他的增删改用executeUpdate()
// 这里得到的int n是影响了多少行数据
int n = ps.executeUpdate();
System.out.println("n = " + n);
MysqlUtil.close(conn);
}
}