使用原生Connection链接
Connection connection = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/data?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true", "root", "root");//获取连接
if (connection == null) {
throw new RuntimeException("数据库链接失败!");
}
//这里必须设置为false,我们手动批量提交
connection.setAutoCommit(false);
PreparedStatement statement = connection.prepareStatement("insert into table " +
"(name, age) " +
"values (?, ?)");
for (String domain : domainList) {
statement.setString(1,"张三");
statement.setInt(2, 18);
//将要执行的SQL语句先添加进去,不执行
statement.addBatch();
}
// 提交要执行的批处理,防止 JDBC 执行事务处理
statement.executeBatch();
connection.commit();
// 关闭相关连接
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
使用注入JdbcTemplate模板
@Autowired
public JdbcTemplate jdbcTemplate;
public void save(){
jdbcTemplate.execute("insert into table(name,age) values('张三',18)");
}
版权声明:本文为u014641168原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。