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

相关推荐

  • 开源免费PHP工具 PHP开发效率提升利器

    推荐开源免费PHP开发工具以提升效率:VS Code、Sublime Text轻量高效,PhpStorm专业强大;调试用Xdebug、Kint、Ray;依赖管理选Composer;代码质量工具包括PHPStan、Psalm、PHP_CodeSniffer;数据库管理可用%ignore_a_1%MyA…

    2026年5月10日
    000
  • Matplotlib 地图中多类型图例的创建与优化

    Matplotlib 地图中多类型图例的创建与优化Matplotlib 地图中多类型图例的创建与优化Matplotlib 地图中多类型图例的创建与优化Matplotlib 地图中多类型图例的创建与优化

    本教程旨在解决matplotlib地图可视化中,如何在一个图例中同时展示颜色块(如区域分类)和自定义标记(如特定兴趣点)的问题。文章详细介绍了当传统`patch`对象无法正确显示标记时,如何利用`matplotlib.lines.line2d`创建标记图例句柄,并将其与颜色块图例句柄合并,从而生成一…

    2026年5月10日 用户投稿
    100
  • Golang JSON序列化:控制敏感字段暴露的最佳实践

    本教程探讨golang中如何高效控制结构体字段在json序列化时的可见性。当需要将包含敏感信息的结构体数组转换为json响应时,通过利用`encoding/json`包提供的结构体标签,特别是`json:”-“`,可以轻松实现对特定字段的忽略,从而避免敏感数据泄露,确保api…

    2026年5月10日
    000
  • 获取日期中的周数:CodeIgniter 教程

    本教程旨在帮助开发者在 CodeIgniter 框架中,从日期字符串中准确提取周数。我们将使用 PHP 内置的 DateTime 类,并提供详细的代码示例和注意事项,确保您能够轻松地在项目中实现此功能。 使用 DateTime 类获取周数 PHP 的 DateTime 类提供了一种便捷的方式来处理日…

    2026年5月10日
    000
  • 比特币新手教程 比特币交易平台有哪些

    比特币是一种去中心化的数字货币,基于区块链技术实现点对点交易,具有匿名性、有限发行和不可篡改等特点;新手可通过交易所购买,P2P交易获得比特币,常用平台包括Binance、OKX和Huobi;交易流程包括注册账户、实名认证、绑定支付方式、充值法币并下单购买,可选择市价单或限价单;比特币存储方式有交易…

    2026年5月10日
    000
  • c++中的SFINAE技术是什么_c++模板编程中的SFINAE原理与应用

    SFINAE 是“替换失败不是错误”的原则,指模板实例化时若参数替换导致错误,只要存在其他合法候选,编译器不报错而是继续重载决议。它用于条件启用模板、类型检测等场景,如通过 decltype 或 enable_if 控制函数重载,实现类型特征判断。尽管 C++20 引入 Concepts 简化了部分…

    2026年5月10日
    000
  • Go语言mgo查询构建:深入理解bson.M与日期范围查询的正确实践

    本文旨在解决go语言mgo库中构建复杂查询时,特别是涉及嵌套`bson.m`和日期范围筛选的常见错误。我们将深入剖析`bson.m`的类型特性,解释为何直接索引`interface{}`会导致“invalid operation”错误,并提供一种推荐的、结构清晰的代码重构方案,以确保查询条件能够正确…

    2026年5月10日
    100
  • RichHandler与Rich Progress集成:解决显示冲突的教程

    在使用rich库的`richhandler`进行日志输出并同时使用`progress`组件时,可能会遇到显示错乱或溢出问题。这通常是由于为`richhandler`和`progress`分别创建了独立的`console`实例导致的。解决方案是确保日志处理器和进度条组件共享同一个`console`实例…

    2026年5月10日
    000
  • Golang goroutine与channel调试技巧

    使用go run -race检测数据竞争,结合runtime.NumGoroutine监控协程数量,通过pprof分析阻塞调用栈,利用select超时避免永久阻塞,有效排查goroutine泄漏、死锁和数据竞争问题。 Go语言的goroutine和channel是并发编程的核心,但它们也带来了调试上…

    2026年5月10日
    000
  • 《魔兽世界》将于6月11日开启国服回归技术测试

    《魔兽世界》将于6月11日开启国服回归技术测试《魔兽世界》将于6月11日开启国服回归技术测试《魔兽世界》将于6月11日开启国服回归技术测试《魔兽世界》将于6月11日开启国服回归技术测试

    《%ign%ignore_a_1%re_a_1%》官方宣布,将于6月11日开启国服回归技术测试,时间为7天,并称可以在6月内正式开服,玩家们可以访问官网下载战网客户端并预下载“巫妖王之怒”客户端,技术测试详情见下图。 WordAi WordAI是一个AI驱动的内容重写平台 53 查看详情 以上就是《…

    2026年5月10日 用户投稿
    200
  • 使用 Jupyter Notebook 进行探索性数据分析

    Jupyter Notebook通过单元格实现代码与Markdown结合,支持数据导入(pandas)、清洗(fillna)、探索(matplotlib/seaborn可视化)、统计分析(describe/corr)和特征工程,便于记录与分享分析过程。 Jupyter Notebook 是进行探索性…

    2026年5月10日
    000
  • 如何在HTML中插入表单元素_HTML表单控件与输入类型使用指南

    HTML表单通过标签构建,包含action和method属性定义数据提交目标与方式,常用input类型如text、password、email等适配不同输入需求,配合label、required、placeholder提升可用性,结合textarea、select、button等控件实现完整交互,是…

    2026年5月10日
    000
  • 创建指定大小并填充特定数据的Golang文件教程

    本文将介绍如何使用Golang创建一个指定大小的文件,并用特定数据填充它。我们将使用 `os` 包提供的函数来创建和截断文件,从而实现快速生成大文件的目的。示例代码展示了如何创建一个10MB的文件,并将其填充为全零数据。掌握这些方法,可以方便地在例如日志系统或磁盘队列等场景中,预先创建测试文件或初始…

    2026年5月10日
    000
  • Python命令怎样使用profile分析脚本性能 Python命令性能分析的基础教程

    使用Python的cProfile模块分析脚本性能最直接的方式是通过命令行执行python -m cProfile your_script.py,它会输出每个函数的调用次数、总耗时、累积耗时等关键指标,帮助定位性能瓶颈;为进一步分析,可将结果保存为文件python -m cProfile -o ou…

    2026年5月10日
    000
  • 如何插入查询结果数据_SQL插入Select查询结果方法

    如何插入查询结果数据_SQL插入Select查询结果方法如何插入查询结果数据_SQL插入Select查询结果方法如何插入查询结果数据_SQL插入Select查询结果方法如何插入查询结果数据_SQL插入Select查询结果方法

    使用INSERT INTO…SELECT语句可高效插入数据,通过NOT EXISTS、LEFT JOIN、MERGE语句或唯一约束避免重复;表结构不一致时可通过别名、类型转换、默认值或计算字段处理;结合存储过程可提升可维护性,支持参数化与动态SQL。 将查询结果数据插入到另一个表中,可以…

    2026年5月10日 用户投稿
    000
  • 使用 WebCodecs VideoDecoder 实现精确逐帧回退

    本文档旨在解决在使用 WebCodecs VideoDecoder 进行视频解码时,实现精确逐帧回退的问题。通过比较帧的时间戳与目标帧的时间戳,可以避免渲染中间帧,从而提高用户体验。本文将提供详细的解决方案和示例代码,帮助开发者实现精确的视频帧控制。 在使用 WebCodecs VideoDecod…

    2026年5月10日
    000
  • PHP动态生成表单输入与POST数据获取实践指南

    本教程详细阐述了如何在php中根据动态数据源(如数据库值)生成多个表单输入框,并演示了如何通过post方法准确无误地获取这些动态生成的输入值。文章强调了正确的输入框命名策略,避免了常见的命名误区,并提供了完整的代码示例,确保开发者能够高效处理动态表单数据。 动态生成表单输入 在Web开发中,我们经常…

    2026年5月10日
    000
  • Debian Copilot的社区活跃度如何

    debian copilot是codeberg社区维护的ai助手,旨在为debian用户提供服务。尽管搜索结果中没有直接提供关于debian copilot社区支持活跃度的具体数据,但我们可以通过debian社区的整体活跃度和特点来推断其活跃性。 Debian社区的一般情况: Debian拥有详尽的…

    2026年5月10日
    000
  • Discord.py 交互按钮超时与持久化解决方案

    本教程旨在解决Discord.py中交互按钮在一段时间后出现“This Interaction Failed”错误的问题。我们将深入探讨视图(View)的超时机制,并提供通过正确设置timeout参数以及利用bot.add_view()方法实现按钮持久化的具体方案,确保您的机器人交互功能稳定可靠,即…

    2026年5月10日
    000
  • JavaScript 动态菜单点击高亮效果实现教程

    本教程详细介绍了如何使用 JavaScript 实现动态菜单的点击高亮功能。通过事件委托和状态管理,当用户点击菜单项时,被点击项会高亮显示(绿色),同时其他菜单项恢复默认样式(白色)。这种方法避免了不必要的DOM操作,提高了性能和代码可维护性,确保了无论点击方向如何,功能都能稳定运行。 动态菜单高亮…

    2026年5月10日
    200

发表回复

登录后才能评论
关注微信