jdbc-db连接和业务调用方发分离

总共分为两块:db连接基础方法+业务调用方使用
1、db连接基础方法
public class DemoForWrite {
static String URL = "jdbc:mysql://127.0.0.1:3306/user";
static String USER_NAME = "root";
static String PASSWORD = "123456";

public static int modify(String sql, List<Object> params) {
try (Connection connection = DriverManager.getConnection(URL, USER_NAME, PASSWORD);

PreparedStatement statement = connection.prepareStatement(sql)) {
for (int i = 0; i < params.size(); i++) {
statement.setObject(i + 1, params.get(i));
}

return statement.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
sql也可以分离出来 
/**
String sql = "update tb_user set name=?,age=? where id=?";
List<Object> params = Lists.newArrayList();
params.add("hehehehe");
params.add(67);
params.add(5);
*/
            
2、业务调用方
public class DemoForWriteApp {
public static void main(String[] args) {
// testInsert();
// testUpdate();
testDelete();
}

private static void testDelete() {
String sql = "delete from tb_user where id=?";
List<Object> params = Lists.newArrayList();
params.add(7);

int rows = DemoForWrite.modify(sql, params);
System.out.println("rows = " + rows);
}

private static void testUpdate() {
String sql = "update tb_user set name=?,age=? where id=?";
List<Object> params = Lists.newArrayList();
params.add("hehehehe");
params.add(67);
params.add(5);

int rows = DemoForWrite.modify(sql, params);
System.out.println("rows = " + rows);
}

private static void testInsert() {
String sql = "insert into tb_user(name,age) values(?,?)";
List<Object> params = Lists.newArrayList();
params.add("xixihaha");
params.add(34);
int rows = DemoForWrite.modify(sql, params);
System.out.println("rows = " + rows);
}
}

jdbc-db连接和业务调用方发分离

上一篇:com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Truncated incorrect DOUBLE value: '张三'异常的解决办法


下一篇:mysql 强制索引和禁止某个索引