
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]); }
发表评论
最新留言
路过,博主的博客真漂亮。。
[***.116.15.85]2025年04月17日 03时33分53秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
3389连接痕迹清除
2019-03-06
发生系统错误 6118
2019-03-06
阿里巴巴Json工具-Fastjson教程
2019-03-06
Spring Cloud Gateway - 快速开始
2019-03-06
Spring Security 实战干货:理解AuthenticationManager
2019-03-06
Java对象转JSON时如何动态的增删改查属性
2019-03-06
Python 面向对象进阶
2019-03-06
Linux常用统计命令之wc
2019-03-06
Git安装及使用以及连接GitHub方法详解
2019-03-06
docker容器与虚拟机的区别
2019-03-06
shell脚本里使用echo输出颜色
2019-03-06
Python2跟Python3的区别
2019-03-06
并发编程——IO模型详解
2019-03-06
Java之封装,继承,多态
2019-03-06
wait()与notify()
2019-03-06
使用js打印时去除页眉页脚
2019-03-06
Spring security OAuth2.0认证授权学习第二天(基础概念-RBAC)
2019-03-06
ORA-00904: "FILED_TYPE": 标识符无效
2019-03-06
数据仓库系列之维度建模
2019-03-06
Scala教程之:函数式的Scala
2019-03-06