首先声明,本文只给出代码,并不是做教程用,如有不便之处,还请各位见谅。

  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操作的更多相关文章

  1. jdbc笔记(一) 使用Statement对单表的CRUD操作

    jdbc连接mysql并执行简单的CRUD的步骤: 1.注册驱动(需要抛出/捕获异常) Class.forName("com.mysql.jdbc.Driver"); 2.建立连接 ...

  2. 【Java EE 学习 44】【Hibernate学习第一天】【Hibernate对单表的CRUD操作】

    一.Hibernate简介 1.hibernate是对jdbc的二次开发 2.jdbc没有缓存机制,但是hibernate有. 3.hibernate的有点和缺点 (1)优点:有缓存,而且是二级缓存: ...

  3. 6.单表的CRUD操作

    1.插入后用新id初始化被插入对象 <insert id="insertStudentCatchId"> insert into student (age,name,s ...

  4. Django学习笔记(10)——Book单表的增删改查页面

    一,项目题目:Book单表的增删改查页面 该项目主要练习使用Django开发一个Book单表的增删改查页面,通过这个项目巩固自己这段时间学习Django知识. 二,项目需求: 开发一个简单的Book增 ...

  5. SQLServer学习笔记<>.基础知识,一些基本命令,单表查询(null top用法,with ties附加属性,over开窗函数),排名函数

    Sqlserver基础知识 (1)创建数据库 创建数据库有两种方式,手动创建和编写sql脚本创建,在这里我采用脚本的方式创建一个名称为TSQLFundamentals2008的数据库.脚本如下:   ...

  6. MyBatis-Plus学习笔记(1):环境搭建以及基本的CRUD操作

    MyBatis-Plus是一个 MyBatis的增强工具,在 MyBatis 的基础上只做增强不做改变,使用MyBatis-Plus时,不会影响原来Mybatis方式的使用. SpringBoot+M ...

  7. Oracle触发器实现监控某表的CRUD操作

    前提:请用sys用户dba权限登录 1.创建一个表来存储操作日志 create table trig_sql( LT DATE not null primary key, SID NUMBER, SE ...

  8. 通过jdbc完成单表的curd操作以及对JDBCUtils的封装

    概述:jdbc是oracle公司制定的一套规范(一套接口),驱动是jdbc的实现类,由数据库厂商提供.所以我们可以通过一套规范实现对不同的数据库操作(多态) jdbc的作用:连接数据库,发送sql语句 ...

  9. JDBC简单增删改查实现(单表)

    0.准备工作 开发工具: MySQL数据库, intelliJ IDEA2017. 准备jar包: mysql-connector-java-5.1.28-bin.jar(其他均可) 1. 数据库数据 ...

随机推荐

  1. Eclipse导出自己的项目(仅供自己保留方式war包)

    War: Jar包:

  2. Web项目中手机注册短信验证码实现的全流程及代码

    最近在做只能净化器的后台用户管理系统,需要使用手机号进行注册,找了许久才大致了解了手机验证码实现流程,今天在此和大家分享一下. 我们使用的是榛子云短信平台, 官网地址:http://smsow.zhe ...

  3. maven打包忽略静态资源解决办法,dispatchServlet拦截静态资源请求的解决办法

    问题: maven 打包时,有的文件打不进去target 解决: 因为maven打包默认打Java文件.在项目中的pom文件中加build标签 <build> <resources& ...

  4. String、StringBuilder以及StringBuffer

    博客地址:https://www.cnblogs.com/dolphin0520/p/3778589.html

  5. python learning day01

    python简介 一.python的由来: python的创始人是吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,吉多·范罗苏姆为了在阿姆斯特丹打发时间,决心开发一个新的脚 ...

  6. 微信小程序轮播图组件 swiper,swiper-item及轮播图片自适应

    官网地址:https://developers.weixin.qq.com/miniprogram/dev/component/swiper.html index.wxml文件 indicator-d ...

  7. Docker File知识

  8. 013-mac重做系统后的软件安装

    一.系统设置 1.屏幕设置:系统偏好设置→显示器→排列,多个显示器可以排列组合 2.touch bar功能键设置:系统偏好设置→键盘→键盘,触控栏设置 F1 3.程序坞[dock]设置:系统偏好设置→ ...

  9. [LeetCode] 115. Distinct Subsequences_ Hard tag: Dynamic Programming

    Given a string S and a string T, count the number of distinct subsequences of S which equals T. A su ...

  10. C# 按不同的字节编码,通过字节数去截取字符串

    /// <summary> /// 按不同的字节编码,通过字节数去截取字符串 /// 数据库UTF-8 1个数字.字母.英文符号算1个长度 1个中文.中文符号算3个长度 /// </ ...