Java PreparedStatement

大家好,很高兴再次与大家见面,我是你们的老朋友全栈君。

Java PreparedStatement与Statement类似,是Java JDBC Framework的一部分。它用于对数据库执行CRUD操作。PreparedStatement扩展了Statement接口。由于支持参数化查询,PreparedStatement被认为更为安全,并且可以防止SQL注入攻击。我们可以通过调用Connection的prepareStatement(String query)方法来获取PreparedStatement的实例,如下所示:

// 方法:public PreparedStatement prepareStatement(String query) throws SQLException {}// 使用:Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/customerdb", "root", "root");PreparedStatement ps = con.prepareStatement("select id, firstname, lastname, email, birthdate from tblcustomer");

PreparedStatement的优势:

PreparedStatement不仅可以用于参数化查询,还可以用于普通查询。其查询性能优于Statement。PreparedStatement的实例可以被重复使用,以执行具有不同参数的同一查询。此外,PreparedStatement可以保护应用程序免受SQL注入攻击。

Java PreparedStatement

立即学习“Java免费学习笔记(深入)”;

Java PreparedStatement层次结构

PreparedStatement方法:

我们可以将方法分为不同的类别。

执行查询:

ResultSet executeQuery():此方法用于通过PreparedStatement对象执行读取操作,返回ResultSet实例以获取数据。int executeUpdate():此方法用于执行插入、删除和更新查询,返回一个整数值,表示受查询影响的数据库行数。

将参数值传递给查询:

所有以下方法都有两个参数。第一个参数是参数索引,第二个参数是参数值。void setInt(int parameterIndex, int value):将Integer值设置为指定的参数索引。void setShort(int parameterIndex, short value):将short值设置为指定的参数索引。void setLong(int parameterIndex, long value):将Long值设置为指定的参数索引。void setFloat(int parameterIndex, float value):将Float值设置为指定的参数索引。void setDouble(int parameterIndex, double value):将Double值设置为指定的参数索引。void setBigDecimal(int parameterIndex, BigDecimal value):将BigDecimal值设置为指定的参数索引。void setString(int parameterIndex, String value):将String值设置为指定的参数索引。void setDate(int parameterIndex, Date value):将Date值设置为指定的参数索引。

注意:参数索引值从1开始,所有这些方法都会抛出SQLException。

Java PreparedStatement示例:

我们将使用MySQL数据库来演示PreparedStatement的使用。使用以下DB脚本创建数据库、表和示例数据:

create database customerdb;use customerdb;create table tblcustomer(    id integer AUTO_INCREMENT primary key,    firstname varchar(32),    lastname varchar(32),    email varchar(32),    birthdate datetime);insert into tblcustomer (id,firstname,lastname,email,birthdate) values(1,'Ricky','Smith','ricky@google.com','2001-12-10');

数据库连接信息:

MySql数据库名称:customerdbIP:localhost端口:3306用户名:root密码:root

Maven依赖关系:

            mysql        mysql-connector-java        5.1.48    

使用PreparedStatement获取数据:

在这种情况下,我们将从tblcustomer表中获取具有指定id的行。查询将返回单行。

package com.journaldev.examples;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;public class PreparedStatementDemo {    public static void main(String[] args) throws Exception {        Connection con = null;        PreparedStatement ps = null;        ResultSet rs = null;        int customerId = 1;        String query = "select id, firstname, lastname, email, birthdate from tblcustomer where id = ?";        try {            Class.forName("com.mysql.jdbc.Driver");            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/customerdb", "root", "root");            ps = con.prepareStatement(query);            ps.setInt(1, customerId);            rs = ps.executeQuery();            while (rs.next()) {                System.out.println("Id:" + rs.getInt(1));                System.out.println("First Name:" + rs.getString(2));                System.out.println("Last Name:" + rs.getString("lastname"));                System.out.println("Email:" + rs.getString("email"));                System.out.println("BirthDate:" + rs.getDate("birthdate"));            }        } catch (Exception e) {            e.printStackTrace();        } finally {            rs.close();            ps.close();            con.close();        }    }}

执行步骤:

步骤1:加载JDBC驱动程序。Class.forName("com.mysql.jdbc.Driver") 将JDBC驱动程序加载到内存中。步骤2:获取Connection对象。DriverManager.getConnection("jdbc:mysql://localhost:3306/customerdb", "root", "root");步骤3:从Connection对象获取PreparedStatement实例,并指定要执行的查询。PreparedStatement ps = con.prepareStatement("select id, firstname, lastname, email, birthdate from tblcustomer");PreparedStatement支持参数化查询,其中’?’是查询中的参数。在执行查询之前,需要提供此参数的值。步骤4:提供查询参数的值。int customerId = 1;ps.setInt(1, customerId); setInt(,)方法有两个参数。在上面的示例中,“1”是参数编号,变量customerId是参数的值。步骤5:执行查询。PreparedStatement的executeQuery()方法用于执行选择查询。它将返回ResultSet的实例。如果查询用于插入、更新或删除,则可以使用executeUpdate()步骤6:迭代ResultSet。ResultSet的next()方法用于获取查询输出。步骤7:关闭资源:这是重要的一步。许多开发人员忘记关闭诸如ResultSet、PreparedStatement和Connection之类的资源。这将导致资源泄漏,可能会使您的应用程序崩溃。

程序输出:

Id:1First Name:RickyLast Name:SmithEmail:ricky@google.comBirthDate:2001-12-1

使用PreparedStatement进行插入操作:

在此示例中,我们将使用PreparedStatement在tblcustomer表中执行插入操作。

package com.journaldev.examples;import java.sql.*;import java.text.SimpleDateFormat;public class PrepareStatementInsertDemo {    public static void main(String[] args) throws Exception {        Connection con = null;        PreparedStatement ps = null;        ResultSet rs = null;        String firstname = "matthew";        String lastname = "wade";        String email = "matthew@java.com";        Date birthdate = new Date(new SimpleDateFormat("YYYY-MM-DD").parse("2000-12-12").getTime());        String query = "insert into tblcustomer (id,firstname,lastname,email,birthdate) values(default,?,?,?,?)";        try {            Class.forName("com.mysql.jdbc.Driver");            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/customerdb", "root", "root");            ps = con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);            ps.setString(1, firstname);            ps.setString(2, lastname);            ps.setString(3, email);            ps.setDate(4, birthdate);            int row = ps.executeUpdate();            System.out.println("No. of Rows inserted:" + row);            rs = ps.getGeneratedKeys();            if (rs.next()) {                System.out.println("Id of new Customer:" + rs.getInt(1));            }        } catch (Exception e) {            e.printStackTrace();        } finally {            rs.close();            ps.close();            con.close();        }    }}

在此示例中,在创建PreparedStatement实例时,我们传递了两个参数。第一个是查询本身,第二个是“Statement.RETURN_GENERATED_KEYS”,这将帮助我们获取新行的主键值。

以下代码用于为插入查询提供参数:

ps.setString(1, firstname);ps.setString(2, lastname);ps.setString(3, email);ps.setDate(4, birthdate);

如前面的程序中所述,executeUpdate()方法用于执行插入操作。它将返回受我们的查询影响的行数。

程序输出:

No. of Rows inserted:1Id of new Customer:2

如果您转到数据库并执行选择查询,您将看到以下结果:

mysql> use customerdb;Database changedmysql> select * from tblcustomer;+----+-----------+----------+------------------+---------------------+| id | firstname | lastname | email            | birthdate           |+----+-----------+----------+------------------+---------------------+|  1 | Ricky     | Smith    | ricky@google.com | 2001-12-10 00:00:00 ||  2 | matthew   | wade     | matthew@java.com | 1999-12-26 00:00:00 |+----+-----------+----------+------------------+---------------------+2 rows in set (0.00 sec)

使用PreparedStatement进行更新操作:

现在我们将执行更新操作。我们将更新电子邮件为“matthew@java.com”的客户的名字和姓氏。这行是在前面的示例中插入的。

package com.journaldev.examples;import java.sql.*;public class PrepareStatementUpdateDemo {    public static void main(String[] args) throws Exception {        Connection con = null;        PreparedStatement ps = null;        String email = "matthew@java.com";        String newFirstname = "john";        String newLastname = "smith";        String query = "update tblcustomer set firstname = ?,lastname =? where email = ?";        try {            Class.forName("com.mysql.jdbc.Driver");            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/customerdb", "root", "root");            ps = con.prepareStatement(query);            ps.setString(1, newFirstname);            ps.setString(2, newLastname);            ps.setString(3, email);            int row = ps.executeUpdate();            System.out.println("No. of Rows Updated:" + row);            if (row == 1) {                String selectQuery = "select id,firstname,lastname,email,birthdate from tblcustomer where email=?";                try (PreparedStatement selStatement = con.prepareStatement(selectQuery);) {                    selStatement.setString(1, email);                    ResultSet rs = selStatement.executeQuery();                    if (rs.next()) {                        System.out.println("Id:" + rs.getInt(1));                        System.out.println("First Name:" + rs.getString(2));                        System.out.println("Last Name:" + rs.getString("lastname"));                        System.out.println("Email:" + rs.getString("email"));                        System.out.println("BirthDate:" + rs.getDate("birthdate"));                    }                    rs.close();                }            }        } catch (Exception e) {            e.printStackTrace();        } finally {            ps.close();            con.close();        }    }}

了解程序:

在上面的示例中,我们在查询中有三个参数。第一个是新名字,第二个是新姓氏,第三个是客户的电子邮件。

以下代码行将此参数的值提供给PreparedStatement:

ps.setString(1, newFirstname);ps.setString(2, newLastname);ps.setString(3, email);

executeUpdate()方法用于执行更新查询。它将返回查询更新的行数。

程序输出:

No. of Rows Updated:1Id:2First Name:johnLast Name:smithEmail:matthew@java.comBirthDate:1999-12-26

您可以使用SQL查询在数据库中检查更新:

mysql> select * from tblcustomer;+----+-----------+----------+------------------+---------------------+| id | firstname | lastname | email            | birthdate           |+----+-----------+----------+------------------+---------------------+|  1 | Ricky     | Smith    | ricky@google.com | 2001-12-10 00:00:00 ||  2 | john      | smith    | matthew@java.com | 1999-12-26 00:00:00 |+----+-----------+----------+------------------+---------------------+2 rows in set (0.00 sec)

使用PreparedStatement进行删除操作:

现在我们将删除电子邮件为“matthew@java.com”的客户记录。

package com.journaldev.examples;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;public class PrepareStatementDeleteDemo {    public static void main(String[] args) throws Exception {        Connection con = null;        PreparedStatement ps = null;        String email = "matthew@java.com";        String query = "delete from tblcustomer where email = ?";        try {            Class.forName("com.mysql.jdbc.Driver");            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/customerdb", "root", "root");            ps = con.prepareStatement(query);            ps.setString(1, email);            int row = ps.executeUpdate();            System.out.println("No. of Rows Deleted:" + row);        } catch (Exception e) {            e.printStackTrace();        } finally {            ps.close();            con.close();        }    }}

PreparedStatement中的批处理方法:

void addBatch():此方法用于将参数集添加到此PreparedStatement对象的批处理中,以更新多行。int[] executeBatch():此方法从PreparedStatement对象的批处理中执行所有SQL查询,并返回更新计数数组。如果此方法无法执行,并且JDBC驱动程序可能会也可能不会继续处理剩余的批处理,则会抛出BatchUpdateException。

使用PreparedStatement的批量/批量操作:

package com.journaldev.examples;import java.sql.*;import java.text.SimpleDateFormat;public class PrepareStatementBatchDemo {    public static void main(String[] args) throws Exception {        Connection con = null;        PreparedStatement ps = null;        ResultSet rs = null;        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD");        String query = "insert into tblcustomer (id,firstname,lastname,email,birthdate) values(default,?,?,?,?)";        try {            Class.forName("com.mysql.jdbc.Driver");            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/customerdb", "root", "root");            ps = con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);            // 1st Insert            ps.setString(1, "Ross");            ps.setString(2, "Southee");            ps.setString(3, "ross@java.com");            ps.setDate(4, new Date(sdf.parse("2000-12-12").getTime()));            ps.addBatch();            // 2nd Insert            ps.setString(1, "Mayank");            ps.setString(2, "Kohli");            ps.setString(3, "mayank@java.com");            ps.setDate(4, new Date(sdf.parse("2005-12-12").getTime()));            ps.addBatch();            // 3rd Insert            ps.setString(1, "Tom");            ps.setString(2, "Patel");            ps.setString(3, "tom@java.com");            ps.setDate(4, new Date(sdf.parse("1995-12-12").getTime()));            ps.addBatch();            // Execution            int[] rows = ps.executeBatch();            for (int row : rows) {                System.out.println("No. of Rows inserted:" + row);            }            rs = ps.getGeneratedKeys();            while (rs.next()) {                System.out.println("Id of new Customer:" + rs.getInt(1));            }        } catch (Exception e) {            e.printStackTrace();        } finally {            rs.close();            ps.close();            con.close();        }    }}

在上面的示例中,我们分批插入了3个客户记录。批量插入多行比单行插入更有效。addBatch()方法将数据添加到批处理中。executeBatch()执行批处理中的所有查询。

输出:

No. of Rows inserted:1No. of Rows inserted:1No. of Rows inserted:1Id of new Customer:10Id of new Customer:11Id of new Customer:12

您可以通过此链接下载完整的Java项目。

参考:Java文档

发布者:全栈程序员栈长,转载请注明出处:https://www.php.cn/link/dbe2b7e940f999dbd70a13eb1da19ea1 原文链接:https://www.php.cn/link/c8377ad2a50fb65de28b11cfc628d75c

以上就是Java PreparedStatement的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/27265.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
《空洞骑士:丝之歌》公布新简中补丁交付时间!建议先用同人汉化
上一篇 2025年11月2日 23:20:38
Java泛型与多态能否结合使用 如何实现通用接口
下一篇 2025年11月2日 23:22:40

相关推荐

  • 如何迁移触发器

    迁移触发器需确保逻辑重建与行为一致,须考虑平台差异、依赖对象及权限。首先确认源与目标数据库对触发事件、时机、级别及功能支持的兼容性,如MySQL支持BEFORE/AFTER行级触发器,SQLite不支持语句级触发器,跨平台可能需重写。接着通过元数据查询或系统表导出触发器定义,如MySQL使用SHOW…

    2026年9月21日
    000
  • 如何下载豆包电脑网页版_豆包电脑网页版正版链接

    豆包AI电脑及网页版可通过官网和官方应用商店安全获取。1、访问https://www.doubao.com登录使用网页版;2、官网下载电脑客户端,支持Windows和macOS;3、通过Microsoft Store或App Store搜索“豆包 AI”,认准北京字节跳动网络技术有限公司开发,确保正…

    2026年9月21日
    100
  • Linux目录结构与文件系统设计理念

    Linux目录结构以根目录为起点,遵循“一切皆文件”理念,通过标准化层级划分(如/bin、/etc、/home等)实现资源统一管理,结合FHS标准、灵活挂载机制与权限模型,提升系统可维护性、安全性和跨发行版兼容性,体现简洁高效的设计哲学。 Linux的目录结构与文件系统设计体现了简洁、统一和高度模块…

    2026年9月21日
    100
  • 如何避免协程中的共享资源竞争?

    避免协程中的共享资源竞争可以通过以下方法:1. 使用锁(locks),如互斥锁或读写锁,确保同一时间只有一个协程访问共享资源。2. 采用无锁数据结构(lock-free data structures),通过原子操作和cas操作提高并发性能。3. 实施消息传递(message passing),通过…

    2026年9月21日
    000
  • mysql如何配置默认存储引擎

    首先查看当前默认存储引擎,通过SHOW VARIABLES命令确认;然后编辑my.cnf或my.ini文件,在[mysqld]下添加default-storage-engine=InnoDB;接着重启MySQL服务使配置生效;最后验证更改结果并检查建表默认引擎。 MySQL 默认存储引擎的配置可以通…

    2026年9月21日
    000
  • Jedis jsonGet 方法返回字节数组值末尾出现 .0 的处理策略

    当使用jedis客户端的`jsonget`方法从redis获取json数据时,如果其中包含字节数组(如xml字符串的字节表示),可能会因底层json库(如gson或org.json)的默认行为,导致数字被统一上转型为`double`类型,从而在输出中显示`.0`后缀。本文将深入探讨此问题产生的原因,…

    2026年9月21日
    200
  • Laravel与Vue.js/React前端框架集成

    laravel可以与vue.js或react集成。1) 使用命令“php artisan preset vue”或“php artisan preset react”设置开发环境。2) 在laravel视图中引入编译后的javascript文件。3) 通过laravel的api路由和前端框架的htt…

    2026年9月21日
    000
  • mysql索引的类型和作用有哪些

    MySQL常见索引类型包括:1. 普通索引用于加速查询;2. 唯一索引确保列值唯一;3. 主键索引为唯一非空且自动创建聚簇索引;4. 聚簇索引决定数据物理存储顺序,每表仅一个;5. 非聚簇索引保存主键值,需回表查询;6. 覆盖索引避免回表提升性能;7. 联合索引遵循最左前缀原则;8. 全文索引支持文…

    2026年9月21日
    000
  • AI推文助手如何制作用户指南 AI推文助手的说明文档创作

    AI推文助手如何制作用户指南 AI推文助手的说明文档创作AI推文助手如何制作用户指南 AI推文助手的说明文档创作AI推文助手如何制作用户指南 AI推文助手的说明文档创作AI推文助手如何制作用户指南 AI推文助手的说明文档创作

    答案:配置账户、设定风格模板、生成推文、安排发布时间、监控数据。依次完成绑定社交账号、选择语气类型与关键词、输入主题生成内容、设置定时发布及查看分析仪表板,实现高效创作与优化。 ☞☞☞AI 智能聊天, 问答助手, AI 智能搜索, 免费无限量使用 DeepSeek R1 模型☜☜☜ 如果您希望使用A…

    2026年9月21日 用户投稿
    000
  • 安卓跑分第一 Redmi K70 至尊版本月发布

    redmi 今日正式宣布,备受期待的 k70 至尊版将于本月盛大发布,预计将与小米 mix 系列折叠旗舰同台竞技,共同演绎科技之美。据官方最新消息,redmi k70 至尊版将搭载联发科天玑 9300+ 处理器,这款处理器在安兔兔跑分测试中一举突破 238 万分大关,目前稳居安卓性能之巅。天玑 93…

    2026年9月21日
    000
  • 如何为特定语言配置VSCode的语法高亮?

    安装对应语言扩展并关联文件类型,可实现VSCode语法高亮。首先通过扩展面板安装目标语言插件,如Ruby或Rust;若文件扩展名未被识别,需手动将扩展名关联至正确语言;最后可在settings.json中配置editor.tokenColorCustomizations来自定义高亮颜色,确保语法解析…

    2026年9月21日
    000
  • Linux怎么使用systemctl管理服务

    Linux怎么使用systemctl管理服务Linux怎么使用systemctl管理服务Linux怎么使用systemctl管理服务Linux怎么使用systemctl管理服务

    systemctl是Linux中管理systemd服务的核心工具,提供统一命令集来启动、停止、重启、查看服务状态及设置开机自启,支持并行启动、依赖管理与Cgroups资源控制,相比SysVinit更高效;通过创建/etc/systemd/system/下的.service文件可自定义服务,包含[Un…

    2026年9月21日 用户投稿
    100
  • Linux如何查看命令别名alias使用方法

    直接输入 alias 命令可列出当前会话所有别名,如需查看特定命令是否为别名可用 type 命令;别名通过简化常用命令提升效率并减少错误,临时别名在当前会话生效,永久别名需写入 ~/.bashrc 或 ~/.zshrc 文件,删除则用 unalias 命令;别名适用于简单命令替换,函数支持参数与逻辑…

    2026年9月21日
    000
  • Java中如何使用Thread.interrupt安全终止线程

    interrupt() 是协作式线程终止机制,设置中断状态并由线程自行处理;2. 阻塞时抛 InterruptedException 且清除状态,需捕获并响应;3. 非阻塞循环中应显式调用 isInterrupted() 检查;4. 捕获异常后应重置中断状态以确保信号传递;5. 使用 Executo…

    2026年9月21日
    200
  • OPPO A3 Pro自动亮度异常解决方法 OPPO A3 Pro屏幕调节技巧

    先检查设置和传感器状态,再排查软硬件问题。关闭省电模式和自动亮度调节,手动调整亮度至50%-70%;清洁屏幕顶部传感器区域,检查手机壳是否遮挡;重启手机,排除第三方应用干扰,更新系统版本;若问题依旧,可能存在非原装屏幕或硬件故障,需联系售后检测。 OPPO A3 Pro出现自动亮度异常,多数情况是设…

    2026年9月21日
    100
  • mysql如何优化子查询

    优先使用JOIN替代相关子查询,减少扫描行数并利用索引;对子查询字段建立合适索引;用EXISTS代替IN处理大量数据;物化不相关子查询结果;避免无索引的标量子查询;通过EXPLAIN分析执行计划优化性能。 MySQL中子查询如果使用不当,容易导致性能下降,尤其是在数据量大的情况下。优化子查询的核心是…

    2026年9月21日
    000
  • 虚拟伴侣AI如何构建记忆库 虚拟伴侣AI长期记忆系统的开发技巧

    虚拟伴侣AI如何构建记忆库 虚拟伴侣AI长期记忆系统的开发技巧虚拟伴侣AI如何构建记忆库 虚拟伴侣AI长期记忆系统的开发技巧虚拟伴侣AI如何构建记忆库 虚拟伴侣AI长期记忆系统的开发技巧虚拟伴侣AI如何构建记忆库 虚拟伴侣AI长期记忆系统的开发技巧

    构建虚拟伴侣AI长期记忆系统需设计分层结构,区分事实、情感与事件记忆,使用向量或图数据库存储并标注元数据;通过自然语言理解提取关键信息,经权重评估后编码存入长期记忆库;借助语义匹配与上下文关联实现记忆唤醒,结合最近邻搜索提升检索效率;引入时间衰减与重复强化机制模拟遗忘规律,定期清理低权记忆;同时实施…

    2026年9月21日 用户投稿
    000
  • 如何在服务器上优化mysql安装

    优化MySQL需从系统环境、配置参数、存储引擎到日常维护多层面入手,首先确保内存合理分配、选用XFS等高性能文件系统、关闭非必要服务并调整内核参数;其次在MySQL配置中优先使用InnoDB引擎,科学设置innodb_buffer_pool_size、innodb_log_file_size、max…

    2026年9月21日
    000
  • 在Java中静态方法能否被重写

    静态方法属于类而非实例,不参与运行时动态绑定,因此不能被重写;2. 子类定义同名静态方法时发生方法隐藏,调用时机由引用类型在编译阶段决定;3. 如示例所示,Parent p = new Child() 调用 p.display() 输出 “Parent static method&#82…

    2026年9月21日
    000
  • Linux怎么监控特定进程的运行状态

    Linux怎么监控特定进程的运行状态Linux怎么监控特定进程的运行状态Linux怎么监控特定进程的运行状态Linux怎么监控特定进程的运行状态

    监控Linux进程需综合使用ps、top、htop、pgrep和systemctl等工具,结合资源占用、进程状态、日志输出和进程数量判断是否异常,并通过systemd的Restart机制或看门狗脚本实现自动重启,同时利用journalctl、sar、atop及Prometheus+Grafana等方…

    2026年9月21日 用户投稿
    000

发表回复

登录后才能评论
关注微信