码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2020-06-10 20:56:04      阅读:68      评论:0      收藏:0      [点我收藏+]

标签:except   modify   dstat   sts   delete   etc   oid   system   app   

总共分为两块: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连接和业务调用方发分离

标签:except   modify   dstat   sts   delete   etc   oid   system   app   

原文地址:https://www.cnblogs.com/duanjialin007/p/13088427.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!