3.JDBC插入
发布日期:2021-05-06 18:58:17 浏览次数:35 分类:精选文章

本文共 1509 字,大约阅读时间需要 5 分钟。

一.普通插入

步骤:

1. 加载驱动并建立连接

2. 编写半成品SQL语句

3. 生成prepareStatement对象

4. 设置参数值,注意索引从1开始

例如:preStmt.setString(1, "王" + i); 对应第一个问号的值

Connection connection = null;  
PreparedStatement preStmt = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/tset04"
+ "?user=root&password=18170021&serverTimezone=UTC";
connection = DriverManager.getConnection(url);
String sql = "insert into book(author,publisher,isbn,pubDate"
+ " ,price) "
+ "values(?,?,?,?,?)";
for (int i = 1; i < 100; i++) {
preStmt = connection.prepareStatement(sql);
preStmt.setString(1, "王" + i);
preStmt.setString(2, "电子" + i);
preStmt.setString(3, "125" + i);
preStmt.setString(4, "2017-5-" + i);
preStmt.setDouble(5, i + 25);
preStmt.executeUpdate();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (preStmt != null) {
try {
preStmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

二.通用插入

思路:

使用函数public void update(String sql, Object… args)来处理不确定参数

通过setObject方法来设置问号对应的值

for (int i = 0; i < args.length; i++) {  
preStmt.setObject(i + 1, args[i]);
}
上一篇:4.JDBC与代码重构
下一篇:2.数据库连接

发表评论

最新留言

路过,博主的博客真漂亮。。
[***.116.15.85]2025年04月17日 03时33分53秒