jdbc笔记(二) 使用PreparedStatement对单表的CRUD操作
首先声明,本文只给出代码,并不是做教程用,如有不便之处,还请各位见谅。
PreparedStatement相较于Statement,概括来说,共有三个优势:
1. 代码的可读性和易维护性:PreparedStatement不需要像Statement那样拼接sql语句,而是用?代替,再对其进行赋值,代码简洁易懂,一目了然。
2. 预编译及DB的缓存过程,使得PreparedStatement在效率上高于Statement。
3. 防止SQL注入(这个不太懂,先这样写着吧)
之前在使用Statement时提过,jdbc的过程大致分为6步(也可以说是7步):注册驱动、建立连接、创建Statement、定义SQL语句、执行SQL语句(如有结果集还需遍历)、关闭连接。PreparedStatement和Statement过程大致相当,不同之处在于,先定义SQL语句,再创建PreparedStatement,再设置参数。总结起来,过程如下:
// 1. 注册驱动
// 2. 建立连接
// 3. 定义sql
// 4. 创建PreparedStatement
// 5. 设置参数
// 6. 执行sql,如果有结果集需遍历并获取
// 7. 关闭资源
下面给出PreparedStatement进行CRUD的代码。
package com.colin.dao; import com.colin.bean.User;
import com.colin.util.DBUtil; import java.sql.*;
import java.util.*; public class PreparedjdbcTest { /**
* 插入一条新记录_PreparedStatement
* @param id id 主键
* @param name 姓名
* @param age 年龄
* @throws SQLException
*/
public static void insert(int id, String name, int age) throws SQLException {
long starttime = System.currentTimeMillis(); PreparedStatement preparedStatement = null;
Connection connection = null;
try {
// 1. 注册驱动
// 2. 建立连接
connection = DBUtil.getConnection();
// 3. 定义sql——?是占位符,在设置参数部分会被替换掉
String sql = "insert into user(id, name, age) values(?, ?, ?)";
// 4. 创建PreparedStatement
preparedStatement = connection.prepareStatement(sql);
// 5. 设置参数
preparedStatement.setInt(1, id);
preparedStatement.setString(2, name);
preparedStatement.setInt(3, age);
// 6. 执行sql,如果有结果集需遍历并获取
int affectrows = preparedStatement.executeUpdate();
System.out.println("affectrows : " + affectrows);
} finally {
// 7. 关闭资源
DBUtil.closeAll(preparedStatement, connection);
} System.out.println("总用时: " + (System.currentTimeMillis() - starttime));
} /**
* 修改一条记录
* @param id
* @param name
* @param age
* @throws SQLException
*/
public static void update(int id, String name, int age) throws SQLException {
long starttime = System.currentTimeMillis(); PreparedStatement preparedStatement = null;
Connection connection = null;
try {
connection = DBUtil.getConnection();
String sql = "update user set name = ?, age = ? where id = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(3, id);
preparedStatement.setString(1, name);
preparedStatement.setInt(2, age);
int affectrows = preparedStatement.executeUpdate();
System.out.println("affectrows : " + affectrows);
} finally {
DBUtil.closeAll(preparedStatement, connection);
} System.out.println("总用时 : " + (System.currentTimeMillis() - starttime)); } /**
* 删除一条记录
* @param id
* @throws SQLException
*/
public static void delete(int id) throws SQLException {
long starttime = System.currentTimeMillis(); PreparedStatement preparedStatement = null;
Connection connection = null;
try {
connection = DBUtil.getConnection();
String sql = "delete from user where id = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, id);
int affectrows = preparedStatement.executeUpdate();
System.out.println("affectrows : " + affectrows);
} finally {
DBUtil.closeAll(preparedStatement, connection);
} System.out.println("总用时 : " + (System.currentTimeMillis() - starttime));
} /**
* 查询一条记录
* @param id
* @throws SQLException
*/
public static List<User> selectOne(int id) throws SQLException { List<User> userList = new ArrayList<>(); ResultSet resultSet = null;
PreparedStatement preparedStatement = null;
Connection connection = null;
try {
// 1. 注册驱动,建立连接
connection = DBUtil.getConnection();
// 2. 定义SQL
String sql = "SELECT id, name, age FROM user WHERE id = ?";
// 3. 创建PreparedStatement
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, id);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
User user = new User(
resultSet.getInt("id"),
resultSet.getString("name"),
resultSet.getInt("age")
);
userList.add(user);
}
} finally {
DBUtil.closeAll(resultSet, preparedStatement, connection);
} return userList;
} /**
* 查询所有记录
* @throws SQLException
*/
public static List<User> selectAll() throws SQLException { List<User> userList = new ArrayList<>(); ResultSet resultSet = null;
PreparedStatement preparedStatement = null;
Connection connection = null;
try {
// 1. 注册驱动,建立连接
connection = DBUtil.getConnection();
// 2. 定义SQL
String sql = "SELECT id, name, age FROM user";
// 3. 创建PreparedStatement
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
User user = new User(
resultSet.getInt("id"),
resultSet.getString("name"),
resultSet.getInt("age")
);
userList.add(user);
}
} finally {
DBUtil.closeAll(resultSet, preparedStatement, connection);
} return userList;
} public static void main(String[] args) throws SQLException { // insert(10,"pestmtName",7);
// update(10, "pestmtName2", 8);
// delete(8); // List<User> userList = selectOne(1);
List<User> userList = selectAll();
System.out.println(userList); }
}
——————————补充:关于增删改的自动提交和手动提交————————————
JDBC中当发生使用DML语言(主要是insert update和delete)时,默认是自动提交的,当然也可以设成手动提交。手动提交需要如下代码(放在获取连接之后):
connection.setAutoCommit(false);
此外,在执行完SQL语句,即preparedStatement.executeXXX()时,需要connection.commit()。需要补充的代码较多,以一个手动提交的insert方法为例:
public static void insert(int id, String name, int age) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DBUtil.getConnection();
connection.setAutoCommit(false);
String sql = "insert into user(id, name, age) values(?, ?, ?)";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, id);
preparedStatement.setString(2, name);
preparedStatement.setInt(3, age);
int affectrows = preparedStatement.executeUpdate();
System.out.println("affectrows : " + affectrows);
// 提交前如果发生异常,如throw new RuntimeException()怎么办?回滚
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
try {
// 别忘了判断connection非空
if (connection != null) {
connection.rollback();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
} finally {
DBUtil.closeAll(preparedStatement, connection);
}
}
完毕。
jdbc笔记(二) 使用PreparedStatement对单表的CRUD操作的更多相关文章
- jdbc笔记(一) 使用Statement对单表的CRUD操作
jdbc连接mysql并执行简单的CRUD的步骤: 1.注册驱动(需要抛出/捕获异常) Class.forName("com.mysql.jdbc.Driver"); 2.建立连接 ...
- 【Java EE 学习 44】【Hibernate学习第一天】【Hibernate对单表的CRUD操作】
一.Hibernate简介 1.hibernate是对jdbc的二次开发 2.jdbc没有缓存机制,但是hibernate有. 3.hibernate的有点和缺点 (1)优点:有缓存,而且是二级缓存: ...
- 6.单表的CRUD操作
1.插入后用新id初始化被插入对象 <insert id="insertStudentCatchId"> insert into student (age,name,s ...
- Django学习笔记(10)——Book单表的增删改查页面
一,项目题目:Book单表的增删改查页面 该项目主要练习使用Django开发一个Book单表的增删改查页面,通过这个项目巩固自己这段时间学习Django知识. 二,项目需求: 开发一个简单的Book增 ...
- SQLServer学习笔记<>.基础知识,一些基本命令,单表查询(null top用法,with ties附加属性,over开窗函数),排名函数
Sqlserver基础知识 (1)创建数据库 创建数据库有两种方式,手动创建和编写sql脚本创建,在这里我采用脚本的方式创建一个名称为TSQLFundamentals2008的数据库.脚本如下: ...
- MyBatis-Plus学习笔记(1):环境搭建以及基本的CRUD操作
MyBatis-Plus是一个 MyBatis的增强工具,在 MyBatis 的基础上只做增强不做改变,使用MyBatis-Plus时,不会影响原来Mybatis方式的使用. SpringBoot+M ...
- Oracle触发器实现监控某表的CRUD操作
前提:请用sys用户dba权限登录 1.创建一个表来存储操作日志 create table trig_sql( LT DATE not null primary key, SID NUMBER, SE ...
- 通过jdbc完成单表的curd操作以及对JDBCUtils的封装
概述:jdbc是oracle公司制定的一套规范(一套接口),驱动是jdbc的实现类,由数据库厂商提供.所以我们可以通过一套规范实现对不同的数据库操作(多态) jdbc的作用:连接数据库,发送sql语句 ...
- JDBC简单增删改查实现(单表)
0.准备工作 开发工具: MySQL数据库, intelliJ IDEA2017. 准备jar包: mysql-connector-java-5.1.28-bin.jar(其他均可) 1. 数据库数据 ...
随机推荐
- Servlet 参数
1.应用参数,在web.xml配置,所有Servlet共用 <context-param> <param-name>driver</param-name> < ...
- js高级的2
BOM0级事件元素绑定多个click最后只执行最后一个click. DOM2级事件元素绑定多个click,都要执行 注意当绑定的多个事件名,函数名,事件发生阶段三者完全一样时,才执行最后一个 div. ...
- 【C++】括号匹配
#include<iostream> #include<cstring> #include<cstdlib> #include<queue> using ...
- 添加一个Button按钮
#增加一个Button 1. 在layout下的xml中添加 <Button android:id="@+id/button1" android:layout_width=& ...
- nodejs实时的检测系统文件的变化(无需重启服务)
1.安装superior npm -g install supervisor 注意 superior必须全局安装,否则错误命令会提示安装到全局 2.修改启动 现在我们需要使用 supervisor a ...
- Python request SSL证书问题
错误信息如下: 1 requests.exceptions.SSLError: ("bad handshake: Error([('SSL routines', 'tls_process_s ...
- HBuilder打包vue项目app后空白,并请求不到数据
(解决空白问题)在打包之前一定要修改 config 目录下的 index.js 文件中的 bulid 模块打包配置项,否则会出现空白,如图 修改前 assetsPublicPath= '/',. ...
- 初入 vue
基于 vue.js 的前端开发环境,用于前后端分离后的单页应用开发. 搭建 vue 项目 按官方指引,使用 vue-cli 搭建 vue 的项目. # 安装依赖库,建议指定 vue 和 element ...
- .net core mysql ef
利用nuget添加以下引用 MySql.Data.EntityFrameworkCore Pomelo.EntityFrameworkCore.MySql Micros ...
- 跨主机网络overlay和macvlan模型
overlay网络模型 无论是openstack还是docker都是先创建一个网络然后再创建虚机或者容器 并把创建的虚机或者容器运行在此网络中 Docker 提供了 overlay driver,使 ...