【WEEK7】 【DAY5】JDBC—PreparedStatement Object【English Version】

2024.4.12 Friday
Following 【WEEK7】 【DAY4】JDBC—Statement Object【English Version】

Contents

  • 10.3.PreparedStatement Object
    • 10.3.1.PreparedStatement can prevent SQL injection, more efficient than statement
    • 10.3.2. Insertion
    • 10.3.3. Deletion
    • 10.3.4. Update
    • 10.3.5. Query
    • 10.3.6. Preventing SQL Injection
      • 10.3.6.1. Under normal circumstances
      • 10.3.6.2. Result
      • 10.3.6.3. SQL Injection Failed
      • 10.3.6.4. Result
  • 10.4. Using IDEA to Connect to the Database
    • 10.4.1. As shown below

10.3.PreparedStatement Object

10.3.1.PreparedStatement can prevent SQL injection, more efficient than statement

10.3.2. Insertion

package lesson.three;import lesson.two.utils.JdbcUtils;import java.sql.*;public class TestInsert {public static void main(String[] args) {Connection conn = null;PreparedStatement st = null;try {conn = JdbcUtils.getConnection();//Difference from a regular statement: uses question marks as placeholdersString sql = "INSERT INTO users(id,`NAME`,`PASSWORD`,`email`,`birthday`) VALUES (?,?,?,?,?)";st = conn.prepareStatement(sql);   //Pre-compile SQL: generate SQL but do not execute//Manually assign values to parameters//The syntax of set... corresponds to each position of the input function parameters and the parameters you wish to setst.setInt(1,4); //idst.setString(2,"lqf");st.setString(3,"987654");st.setString(4,"27046873@qq.com");st.setDate(5,new java.sql.Date(new java.util.Date().getTime()));//new Date().getTime() means: the time calculated by the computer needs to be converted to MySQL time//sql.Date is database time, util.Date is Java's//Because the source code of setDate has the time parameter as the database type: void setDate(int parameterIndex, java.sql.Date x)//So, we need to use new Date().getTime() to get the timestamp (in this version, using “new java.util.Date().getTime()” does not cause an error)//Executeint i = st.executeUpdate();if(i > 0){System.out.println("Insertion successful");}} catch (SQLException e) {e.printStackTrace();} finally {JdbcUtils.release(conn,st,null);}}
}
  • Result
    Insert picture description here
    Insert picture description here

10.3.3. Deletion

package lesson.three;import lesson.two.utils.JdbcUtils;import java.sql.*;public class TestDelete {public static void main (String[] args) {Connection conn = null;PreparedStatement st = null;try {conn = JdbcUtils.getConnection();//Difference from a regular statement: uses question marks as placeholdersString sql = "DELETE FROM users WHERE id = ?";st = conn.prepareStatement(sql);   //Pre-compile SQL: generate SQL but do not execute//Manually assign values to parametersst.setInt(1,4); //id//Executeint i = st.executeUpdate();if(i > 0){System.out.println("Deletion successful");}} catch (SQLException e) {e.printStackTrace();} finally {JdbcUtils.release(conn,st,null);}}
}
  • Result
    Insert picture description here
    Insert picture description here
    *After completing the code, if there’s no option to run: generally means the system didn’t detect the main function -> The most basic error is a spelling mistake in the main function, check this first before searching online for other possibilities.

10.3.4. Update

package lesson.three;import lesson.two.utils.JdbcUtils;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;public class TestUpdate {public static to main(String[] args){Connection conn = null;PreparedStatement st = null;try {conn = JdbcUtils.getConnection();//Difference from a regular statement: uses question marks as placeholdersString sql = "UPDATE users SET `NAME` = ? WHERE id = ?";st = conn.prepareStatement(sql);   //Pre-compile SQL: generate SQL but do not execute//Manually assign values to parametersst.setString(1,"阿布巴卡");st.setInt(2,1); //id//Executeint i = st.executeUpdate();if(i > 0){System.out.println("Update successful");}} catch (SQLException e) {e.printStackTrace();} finally {JdbcUtils.release(conn,st,null);}}
}
  • Result
    Insert picture description here
    Insert picture description here
    Here’s the translation:

10.3.5. Query

package lesson.three;import lesson.two.utils.JdbcUtils;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;public class TestSelect {public static void main(String[] args){Connection conn = null;PreparedStatement st = null;ResultSet rs = null;try {conn = JdbcUtils.getConnection();//Write SQLString sql = "SELECT * FROM users WHERE id = ?";st = conn.prepareStatement(sql);   //Pre-compile SQL: generate SQL but do not execute//Pass parametersst.setInt(1,1); //id//Executers = st.executeQuery();if(rs.next()){System.out.println(rs.getString("NAME"));}} catch (SQLException e) {e.printStackTrace();} finally {JdbcUtils.release(conn,st,rs);}}
}
  • Result
    Insert picture description here

10.3.6. Preventing SQL Injection

10.3.6.1. Under normal circumstances

package lesson.three;import lesson.two.utils.JdbcUtils;import java.sql.*;public class prevent_SQL_injection {public static void main(String[] args){login("Abubakar","123456"); //Under normal circumstances
//        login("''or '1=1 ","'or '1=1 "); //sql injection}//Login servicepublic static void login(String username, String password){Connection conn = null;PreparedStatement st = null;ResultSet rs = null;try {conn = JdbcUtils.getConnection();//SQLString sql = "SELECT * FROM users WHERE `NAME`=? AND `PASSWORD`=?";st = conn.prepareStatement(sql);st.setString(1,username);st.setString(2,password);//The result set returned after the query is saved in rsrs = st.executeQuery(); //The sql in the brackets should be deleted, otherwise it throws an error, but the reason is unknown//Printwhile (rs.next()) {System.out.println(rs.getString("NAME"));System.out.println(rs.getString("email"));System.out.println(rs.getString("password"));System.out.println("===========================");}} catch (SQLException e) {throw new RuntimeException(e);} finally {JdbcUtils.release(conn,st,rs);}}
}

10.3.6.2. Result

Insert picture description here

10.3.6.3. SQL Injection Failed

Only modify the login statement

login("''or '1=1 ","'or '1=1 "); //sql injection

10.3.6.4. Result

(No results found)
Insert picture description here

10.4. Using IDEA to Connect to the Database

10.4.1. As shown below

Insert picture description here
Insert picture description here
Insert picture description here
In theory, it’s fine as long as it’s successful, but in practice, it’s almost never needed.
Create a table under the p37jdbc database and insert data through IDEA:

-- P44
-- Create user table
CREATE TABLE account(id INT PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(40),money FLOAT
);
-- Insert test data
INSERT INTO account(`NAME`, money) VALUES ('A', 1000);
INSERT INTO account(`NAME`, money) VALUES ('B', 1000);
INSERT INTO account(`NAME`, money) VALUES ('C', 1000);

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/617465.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

我五年减脂历程中应用的数据指标

对于减脂,理论说的再多无益,关键是要行动起来。只有坚持过,才有资格说:我尽力了。 每天跑步5公里,是改变一个人体态的分水岭。记住是每天,不管春夏秋冬、酷暑寒雪。 我常在想,如何才能变成一个更…

微服务项目——谷粒商城

文章目录 一、项目简介(一)完整的微服务架构详细解释——微服务划分图(二)电商模式1.B2B 模式2.B2C 模式3.C2B 模式4.C2C 模式5.o2o 模式2.谷粒商城 (三)项目技术&特色(四)项目前…

DHCP是什么意思 路由器中DHCP服务器怎么设置?

概述 DHCP是什么意思?很多朋友在路由器设置中,都会看到有一项“DHCP服务器”设置功能,而很多朋友对这个功能不太了解,也不知道怎么设置。其实,对于普通用户来说,无需去单独设置路由器DHCP服务器功能&#…

数据库SQL语言实战(一)

目录 创建SQL表 题目一 题目二 题目三 插入数据 题目一 题目二 题目三 总结 创建SQL表 题目一 创建学生信息表(学生编号、姓名、性别、年龄、出生日期、院系名称、班级): test1_student:sid char 12 not null、nam…

AIGC 技术及应用初探

ChatGPT 相关话题近一年多来被刷爆,利用 AI 技术生成内容,引起了各行各业的关注。其实,自2022 年 4 月起,OpenAI、Google、Microsoft 相继发布了文生图模型,视觉创作就已经开始持续火热了。国内 AIGC 相关的技术和应用…

python基础——类型注解【变量,函数,Union】

📝前言: 上一篇文章Python基础——面相对象的三大特征提到,python中的多态,python中,类型是动态的,这意味着我们不需要在声明变量时指定其类型。然而,这可能导致运行时错误,因为我们…

The C programming language (second edition,KR) exercise(CHAPTER 3)

E x c e r c i s e 3 − 1 Excercise\quad 3-1 Excercise3−1:输出结果如图1所示,这里故意让二分搜索算法去寻找一个在数组中不存在在的数,然后去看两种二分搜索算法分别所花费的时间的大小,为了使得所花费的时间更具有可分辨性&a…

SAP SD学习笔记05 - SD中的一括处理(集中处理),出荷和请求的冻结(替代实现承认功能)

上一章讲了SD的重要概念,比如出荷Plant(交货工厂),出荷Point(装运点),输送计划,品目的可用性检查,一括纳入/分割纳入,仓库管理等。 SAP SD学习笔记04 - 出荷…

机器学习—特征工程(三)

什么是特征工程 特征工程是使用专业背景知识和技巧处理数据,使得特征能在机器学习算法上发挥更好的作用的过程。 意义︰会直接影响机器学习的效果 特征工程的位置与数据处理的比较 pandas:—个数据读取非常方便以及基本的处理格式的工具sklearn:对于特征的处理提…

某网站sign签名参数与数据响应加密逆向分析

文章目录 1. 写在前面2. 接口分析3. 断点分析4. 扣代码 【🏠作者主页】:吴秋霖 【💼作者介绍】:擅长爬虫与JS加密逆向分析!Python领域优质创作者、CSDN博客专家、阿里云博客专家、华为云享专家。一路走来长期坚守并致力…

Nature Machine Intelligence 纽约大学团队提出基于深度学习和语音生成技术的脑电-语音解码

由于神经系统的缺陷导致的失语会导致严重的生活障碍,它可能会限制人们的职业和社交生活。近年来,深度学习和脑机接口(BCI)技术的飞速发展为开发能够帮助失语者沟通的神经语音假肢提供了可行性。开发神经-语音解码器的尝试大多数依…

大模型实战案例:8卡环境微调马斯克开源大模型 Grok-1

节前,我们星球组织了一场算法岗技术&面试讨论会,邀请了一些互联网大厂朋友、参加社招和校招面试的同学,针对算法岗技术趋势、大模型落地项目经验分享、新手如何入门算法岗、该如何准备、面试常考点分享等热门话题进行了深入的讨论。 汇总…