PreparedStatement类详解以及案例_东方-教育技术博主的博客-程序员秘密

技术标签: preparedstatement  java  真实项目  数据库  

一:jdbc

(1) 注册驱动
(2)获得链接:
(3)获得sql 容器: Statement :
(4)执行sql 语句:
(5)查询操作, 需要遍历结果集:
(6)关闭资源:

Statement: 存在的弊端, 可以被sql 注入:
所以实际开发是不在地用的

PreparedStatement: 类:

简单介绍:

java.sql包中的**PreparedStatement 接口继承了Statement,**并与之在两方面有所不同:有人主张,在JDBC应用中,如果你已经是稍有水平开发者,你就应该始终以PreparedStatement代替Statement.也就是说,在任何时候都不要使用Statement。

作用:
(1)带有预编译的功能:
(2)效率高:
(3)防止sql 注入:

传统的方式: 当执行到sql 语句的时候,sql 语句才能够被编译, 执行:
stmt = conn.createStatement();
String sql =“select * from student where password =’+password+’” and username=’"+username+"’;
stmt.execuete(sql);

预编译:
String sql =“select * from student where password = ? and username =?”;
conn.prepareStatement(String sql); 获得容器的时候, sql 给定: sql预编译:

占位符有几个参数就设置几个,student类的dao层----------增删改查的方法如下:

package com.yidongxueyuan.dao.impl;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.yidongxueyuan.dao.StudentDao;
import com.yidongxueyuan.domain.Student;
import com.yidongxueyuan.utils.JdbcUtil;

public class StudentDaoImpl implements StudentDao {

	@Override
	public void saveStudent(Student stu) {
		
		Connection  conn = JdbcUtil.getConnection();
		PreparedStatement stmt=null; 
		try {
			String sql ="insert into student(sname, birthday) values(?,?)"; 
			stmt = conn.prepareStatement(sql);
			
			//通过预编译对象: 给占位符进行设置值: 
			stmt.setString(1, stu.getSname()); 
			stmt.setDate(2, stu.getBirthday());
			
			
			//语句的执行: 一定要放在 设置占位符之后: 
			int num = stmt.executeUpdate();
			System.out.println(num);
		} catch (SQLException e) {
		
			e.printStackTrace();
		} finally{
			JdbcUtil.release(null, stmt, conn);
		}
		
	}

	@Override
	public void deleteStudentById(String id) {
		Connection  conn = JdbcUtil.getConnection();
		PreparedStatement stmt=null; 
		try {
			String sql ="delete from student where sid=?"; 
			stmt = conn.prepareStatement(sql);
			
			//设置占位符: 
			stmt.setString(1, id);
			
			
			//语句的执行: 一定要放在 设置占位符之后: 
			int num = stmt.executeUpdate();
			System.out.println(num);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			JdbcUtil.release(null, stmt, conn);
		}
	}

	@Override
	public void updateStudent(Student stu) {
		Connection  conn = JdbcUtil.getConnection();
		PreparedStatement stmt=null; 
		try {
			String sql ="update student set sname=? where sid=?"; 
			stmt = conn.prepareStatement(sql);
			
			//设置占位符: 
			stmt.setString(1, stu.getSname());
			stmt.setString(2, stu.getSid());
			
			
			//语句的执行: 一定要放在 设置占位符之后: 
			int num = stmt.executeUpdate();
			System.out.println(num);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			JdbcUtil.release(null, stmt, conn);
		}
		
	}

	@Override
	public Student findById(String id) {
		Connection  conn = JdbcUtil.getConnection();
		PreparedStatement stmt=null; 
		 ResultSet rs=null; 
		try {
			String sql =" select * from student where sid=?"; 
			stmt = conn.prepareStatement(sql);
			
			//设置占位符: 
			stmt.setString(1, id);
			
			//语句的执行: 一定要放在 设置占位符之后: 
		     rs = stmt.executeQuery();
		     
			 if(rs.next()){
				 Student stu = new Student(); 
				 String sid = rs.getString("sid");
				 String name = rs.getString("sname");
				 Date date = rs.getDate("birthday");
				 stu.setSid(sid); 
				 stu.setSname(name);
				 stu.setBirthday(date);
				 return stu; 
			 }
			return null; 
		} catch (SQLException e) {
			throw new RuntimeException(e);
		} finally{
			JdbcUtil.release(rs, stmt, conn);
		}
	}

	@Override
	public List<Student> findAll() {
		Connection  conn = JdbcUtil.getConnection();
		PreparedStatement stmt=null; 
		 ResultSet rs=null; 
		try {
			String sql =" select * from student "; 
			stmt = conn.prepareStatement(sql);
			
			
			//语句的执行: 一定要放在 设置占位符之后: 
		     rs = stmt.executeQuery();
		     
		     List<Student> list = new ArrayList<Student>(); 
			 while(rs.next()){
				 Student stu = new Student(); 
				 String sid = rs.getString("sid");
				 String name = rs.getString("sname");
				 Date date = rs.getDate("birthday");
				 stu.setSid(sid); 
				 stu.setSname(name);
				 stu.setBirthday(date);
				 list.add(stu);
			 }
			return list; 
		} catch (SQLException e) {
			throw new RuntimeException(e);
		} finally{
			JdbcUtil.release(rs, stmt, conn);
		}
	}
	
}

二: 案例:

(1)加了+
访问当前项目的: http://localhost:8080/javaEE-18/index.jsp ----》登录:

注册: ------》 登录: ------》 展示了所有的用户信息: id username password :

(2)

列表的展示: 查询所有:
查询: 根据id 进行查询:
修改: 先根据id 将对象进行查询, 展示在页面上, 修改完成后, 进行save
添加:
删除: 根据id 进行删除:
批量删除:

(3) 底层数据库的搭建:

实现步骤:
创建数据库表:
在这里插入图片描述
 
创建一个customer 表:

CREATE TABLE Customers(
id VARCHAR (100) PRIMARY KEY,
NAME VARCHAR(100),
gender VARCHAR(10),
birthday DATE ,
phonenum VARCHAR(100),
email VARCHAR(100),
hobby VARCHAR(255),
TYPE VARCHAR(10),
description LONGTEXT
)

接着是mvc三层:

dao层:

接口:

package com.yidongxueyuan.dao;

import java.util.List;

import com.yidongxueyuan.domain.Customer;

public interface CustomerDao {

	List<Customer> findAll();

	Customer findById(Customer cus);

	void updateCustomer(Customer customer);

	void deleteById(Customer cus);

	void addCustomer(Customer customer);

	

}

实现类:

package com.yidongxueyuan.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.yidongxueyuan.dao.CustomerDao;
import com.yidongxueyuan.domain.Customer;
import com.yidongxueyuan.utils.JdbcUtil;

public class CustomerDaoImpl implements CustomerDao {

	@Override
	public List<Customer> findAll() {
		Connection  conn = JdbcUtil.getConnection();
		PreparedStatement stmt=null; 
		 ResultSet rs=null; 
		try {
			String sql =" select * from Customers "; 
			stmt = conn.prepareStatement(sql);
			
			//语句的执行: 一定要放在 设置占位符之后: 
		     rs = stmt.executeQuery();
		     List<Customer> list = new ArrayList<Customer>(); 
			 while(rs.next()){
				 Customer c = new Customer(); 
				 c.setId(rs.getString("id"));
				 c.setName(rs.getString("name")); 
				 c.setGender(rs.getString("gender")); 
				 c.setBirthday(rs.getDate("birthday")); 
				 c.setPhonenum(rs.getString("phonenum")); 
				 c.setHobby(rs.getString("hobby"));
				 c.setEmail(rs.getString("email")); 
				 c.setType(rs.getString("type"));
				 c.setDescription(rs.getString("description"));
				 list.add(c);
			 }
			 return list;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		} finally{
			JdbcUtil.release(rs, stmt, conn);
		}
	}

	@Override
	public Customer findById(Customer cus) {
		Connection  conn = JdbcUtil.getConnection();
		PreparedStatement stmt=null; 
		 ResultSet rs=null; 
		try {
			String sql =" select * from Customers where id=?"; 
			stmt = conn.prepareStatement(sql);
			
			//设置占位符: 
			stmt.setString(1, cus.getId());
			
			//语句的执行: 一定要放在 设置占位符之后: 
		     rs = stmt.executeQuery();
		     
			 if(rs.next()){
				 Customer c = new Customer(); 
				 c.setId(rs.getString("id"));
				 c.setName(rs.getString("name")); 
				 c.setGender(rs.getString("gender")); 
				 c.setBirthday(rs.getDate("birthday")); 
				 c.setPhonenum(rs.getString("phonenum")); 
				 c.setHobby(rs.getString("hobby"));
				 c.setEmail(rs.getString("email")); 
				 c.setType(rs.getString("type"));
				 c.setDescription(rs.getString("description"));
				 return c; 
			 }
			return null; 
		} catch (SQLException e) {
			throw new RuntimeException(e);
		} finally{
			JdbcUtil.release(rs, stmt, conn);
		}
		
	}

	@Override
	public void updateCustomer(Customer customer) {
		Connection  conn = JdbcUtil.getConnection();
		PreparedStatement stmt=null; 
		try {
			String sql ="update customers set NAME=?, gender=?,birthday=?,phonenum=?,email=?,hobby=?,TYPE=?,description=? where id=?"; 
			stmt = conn.prepareStatement(sql);
			
			stmt.setString(1, customer.getName());
			stmt.setString(2, customer.getGender());
			stmt.setDate(3, new java.sql.Date(customer.getBirthday().getTime()));
			stmt.setString(4, customer.getPhonenum());
			stmt.setString(5, customer.getEmail());
			stmt.setString(6, customer.getHobby());
			stmt.setString(7, customer.getType());
			stmt.setString(8, customer.getDescription());
			stmt.setString(9, customer.getId()); 
			
			//语句的执行: 一定要放在 设置占位符之后: 
			int num = stmt.executeUpdate();
			System.out.println(num);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			JdbcUtil.release(null, stmt, conn);
		}
		
	}

	@Override
	public void deleteById(Customer cus) {
		Connection  conn = JdbcUtil.getConnection();
		PreparedStatement stmt=null; 
		try {
			String sql ="delete from customers where id=? "; 
			stmt = conn.prepareStatement(sql);
			
			//设置占位符: 
			stmt.setString(1, cus.getId());
			
			//语句的执行: 一定要放在 设置占位符之后: 
			int num = stmt.executeUpdate();
			System.out.println(num);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			JdbcUtil.release(null, stmt, conn);
		}
		
	}

	@Override
	public void addCustomer(Customer customer) {
		Connection  conn = JdbcUtil.getConnection();
		PreparedStatement stmt=null; 
		try {
			String sql =" insert into customers(id,NAME, gender,birthday,phonenum,email,hobby,TYPE,description) " +
					"values(?,?,?,?,?,?,?,?,?)"; 
			stmt = conn.prepareStatement(sql);
			
			//通过预编译对象: 给占位符进行设置值: 
			stmt.setString(1, customer.getId()); 
			stmt.setString(2, customer.getName());
			stmt.setString(3, customer.getGender());
			stmt.setDate(4, new java.sql.Date(customer.getBirthday().getTime()));
			stmt.setString(5, customer.getPhonenum());
			stmt.setString(6, customer.getEmail());
			stmt.setString(7, customer.getHobby());
			stmt.setString(8, customer.getType());
			stmt.setString(9, customer.getDescription());
			
			
			//语句的执行: 一定要放在 设置占位符之后: 
			int num = stmt.executeUpdate();
			System.out.println(num);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			JdbcUtil.release(null, stmt, conn);
		}
		
	}
	
}

service层:

接口:

package com.yidongxueyuan.service;

import java.util.List;

import com.yidongxueyuan.domain.Customer;

/*
 * 设计业务接口: 
 */
public interface BusinessService {

	/**
	 * 添加的方法:
	 * @param customer 传递的是customer 对象: 
	 */
	void addCustmer(Customer customer);
	
	/**
	 * 删除的方法: 
	 * @param id
	 */
	void deleteById(Customer id);
	
	/**
	 * 修改的方法: 
	 * @param customer
	 */
	void updateCustomer(Customer customer); 
	
	/**
	 * 唯一性查询查询方法: 
	 * @param id
	 * @return
	 */
	Customer findById(Customer id);
	
	
	/**
	 *  查询所有:
	 * @return
	 */
	List<Customer> findAll();
	
	
	
}

实现类:

package com.yidongxueyuan.service.impl;

import java.util.List;

import com.yidongxueyuan.dao.CustomerDao;
import com.yidongxueyuan.dao.impl.CustomerDaoImpl;
import com.yidongxueyuan.domain.Customer;
import com.yidongxueyuan.service.BusinessService;

/**
 * 业务层的实现类: 
 * @author Mrzhang
 * @version 2.0 
 * @See  customer1.0 
 * 
 */
public class BusinessServiceImpl implements BusinessService {

	//依赖dao层: 
	private CustomerDao dao = new CustomerDaoImpl();
	@Override
	public void addCustmer(Customer customer) {
		if(customer == null){
			throw new IllegalArgumentException("customer对象不能为null");
		}
		
		dao.addCustomer(customer);
	}

	@Override
	public void deleteById(Customer cus) {
		if(cus.getId() == null || cus.getId().trim().equals("")){
			throw new IllegalArgumentException("customer的id" +
					" 必须填写, 不能为空");
		}
		
		dao.deleteById(cus);

	}

	@Override
	public void updateCustomer(Customer customer) {
		if(customer == null){
			throw new IllegalArgumentException("customer对象不能为null");
		}
		
		dao.updateCustomer(customer);

	}

	@Override
	public Customer findById(Customer cus) {
		if(cus.getId() == null || cus.getId().trim().equals("")){
			throw new IllegalArgumentException("customer的id" +
					" 必须填写, 不能为空");
		}
		
		Customer customer = dao.findById(cus);
		return customer;
	}


	@Override
	public List<Customer> findAll() {
		List<Customer> list = dao.findAll();
		return list;
	}

}

测试service层:

package com.yidongxueyuan.test;

import java.util.Date;
import java.util.List;

import org.junit.Test;

import com.yidongxueyuan.domain.Customer;
import com.yidongxueyuan.service.BusinessService;
import com.yidongxueyuan.service.impl.BusinessServiceImpl;

public class CustomerDaoImplTest {
	
	private BusinessService s= new BusinessServiceImpl();
	//增加: 
	@Test
	public void test1() throws Exception {
		Customer c= new Customer("1002", "宋坤2", "男", new Date(), "18811307278", "[email protected]", "女", "svip", "好男人");
		s.addCustmer(c);
	}
	
	
	//唯一性查询: 
	@Test
	public void test2() throws Exception {
		Customer cus=new Customer();
		cus.setId("1001");
		Customer c = s.findById(cus);
		System.out.println(c);
	}
	//全查询:  
		@Test
		public void test3() throws Exception {
			 List<Customer> list = s.findAll();
			System.out.println(list);
		}
		
		//删除
		@Test
		public void test4() throws Exception {
			Customer cus=new Customer();
			cus.setId("1001");
			s.deleteById(cus);
		}
		//更新
		@Test
		public void test5() throws Exception {
			Customer cus=new Customer();
			cus.setId("1002");
			
			Customer c = s.findById(cus);
		    c.setName("飞鹏");
		    
		    s.updateCustomer(c);
		    
		}
		
		
}

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_41517071/article/details/84656699

智能推荐

Python 使用docx库操作word文档中的表格单元格内容_python 读取docx表格_Hushi1706IT的博客-程序员秘密

(2)修改单元格整体内容。(3)修改单元格段落内容。(1)获取单元格对象。

Bootstrap基本介绍及运用_前端框架bootstrap作用_【小袁】的博客-程序员秘密

一,Bootstrap是什么?一,Bootstrap是什么?1.1Bootstrap诞生于2011年,来自Twitter公司,是目前最受前端框架1.2是一个用于快速开发Web应用程序和网站的前端框架1.3Bootstrap是基于HTML,CSS,JS的,简单灵活,使得Web开发更加快捷概述:Bootstrap是一个建立一个页面,就可以在三个终端(pc端,平板,手机)上完美展示的响应式前端框架...

如何在Linux数据中心服务器上重新平衡btrfs文件系统?_btrfs balance_oMcLin的博客-程序员秘密

btrfs文件系统正在迅速普及,它在许多Linux发行版上使用,并提供了许多在数据中心环境中很有意义的功能–比如快照、负载平衡、在线碎片整理、池化和错误检测。要充分利用btrfs文件系统,你需要知道如何使用一些更高级的功能。其中一个这样的功能叫做平衡(或重新平衡)。为什么你需要平衡btrfs文件系统使用一个两级分配器。第一阶段为特定类型的数据(数据、元数据、系统)分配大块。第二阶段分配较小的块,如文件系统。然而,可能发生的情况是,当文件系统用完了数据或元数据的空间,无法分配新的块。如何运行测试当

Nginx中rewrite实现二级域名、三级域名、泛域名、路径的重写_nginx 三级域名_wit_cx的博客-程序员秘密

最常见的: 静态地址重定向到带参数的动态地址rewrite "^(.*)/service/(.*)\.html$" $1/service.php?sid=$2 permanent; 反过来: 带参数的动态地址重定向到静态地址if($query_string~*id=(.*)){ set$id$1; rewrite"^(.*)/article.asp$"$1/article/$id.htmlast; }泛域名解析server_na...

多线程异步提高RK3588的NPU占用率,进而提高yolov5s帧率_算尽为数的博客-程序员秘密

作者手头上有一块香橙派5,其搭载有一颗三核心6TOPS算力的NPU, 由于发布时间不长,社区的资料还是比较匮乏, 所以在这里写一下关于如何提高NPU使用率的教程文章和代码使用yolov5s进行讲解, 其他模型如resnet之类的同理,稍作修改就可以使用。由于已经有很多人,如等做了如何通过修改模型提高视频推理帧率的教程, 这里我就主要讲另外一种性能的方法——多线程异步。

RxJava+Retrofit+Mvp实现购物车(没有结算页面)_小黑子爱敲代码的博客-程序员秘密

先给大家展示一下效果图 框架结构: 1.项目框架:MVP,图片加载用Fresco,网络请求用OKhttp+Retrofit实现(自己封装,加单例模式), 2.完成购物车数据添加(如果接口无数据,可用接口工具添加数据), 3.自定义view实现加减按钮,每次点击加减,item中的总数及总价要做出相应的改变。 4.当数量为1时,点击减号,数量不变,吐司提示用户最小数量为1。 5.底部总

随便推点

js作品()Hbuilder_使用hbuilder将前端搜索功能实现_wumeng5211314的博客-程序员秘密

&amp;lt;!DOCTYPE html&amp;gt;&amp;lt;html&amp;gt;    &amp;lt;head&amp;gt;        &amp;lt;meta charset=&quot;UTF-8&quot;&amp;gt;        &amp;lt;title&amp;gt;&amp;lt;/title&amp;gt;        &amp;lt;script src=&quot;js/angular.min.js&quot; type=&quot;text/javas

ACE中的设计模式(3)——Strategy_ace_thread_strategy_JoiseLI的博客-程序员秘密

 ACE中的设计模式(3)——StrategyJoise.LI @ 2006-10-9,FYT04121 1.         Strategy模式简介Strategy模式定义了不同算法的接口,分别封装起来,让他们彼此之间可以互相替换,带来的好处是把系统中容易发生变化的部分与稳定的部分隔离开来,该模式对于后续的维护是非常有用的。使用Strategy可以应对不稳定的需求,对于

[JAVA]定时任务之-Quartz使用篇_diaokai2608的博客-程序员秘密

[BAT][JAVA]定时任务之-Quartz使用篇定时任务之-Quartz使用篇 Quartz是OpenSymphony开源组织在Job scheduling领域又一个开源项目,它可以与J2EE与J2SE应用程序相结合也可以单独使用。Quartz可以用来创建简单或为运行十个,百个,甚至是好几万个Jobs这样复杂的日程序表。Jobs可以做成...

React原生 实现公告无限滚动效果_react 滚动通知_big tail的博客-程序员秘密

React原生 实现公告无限滚动效果//index.jsimport React, { Component } from 'react'import './index.less'export default class Scroll extends Component { constructor(props) { super(props); this.state = { noticeList: [ {

C语言程序设计经典例题(考研必背)(基础篇)第一周_手机只用华为的博客-程序员秘密

一,求三个整数的最大值#include &lt;stdio.h&gt;int main(void){int a, b, c;int x=0;printf(“请输入三个数:\n”);scanf("%d %d %d",&amp;a,&amp;b,&amp;c);if(a&gt;b&amp;&amp;a&gt;c) x=a;if(b&gt;a&amp;&amp;b&gt;c) x=...

js调用百度地图获取经纬度以及详细坐标_js使用百度地图获取经纬度_晨光熹微,努力把每一天的熹光都变为晨光的博客-程序员秘密

js调用百度地图获取经纬度以及详细坐标&lt;!DOCTYPE html&gt;&lt;html lang="en"&gt;&lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;Title&lt;/title&gt; &lt;script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&amp;ak=0FuoX30MFf7YMrdS5Wi9GGA