import com.loaderman.util.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import org.junit.Test;
/**
* PreparedStatement執行sql語句
*
*/
public class Demo1 { /**
* 增加
*/
@Test
public void testInsert() {
Connection conn = null;
PreparedStatement stmt = null;
try {
//1.获取连接
conn = JdbcUtil.getConnection(); //2.准备预编译的sql
String sql = "INSERT INTO student(NAME,gender) VALUES(?,?)"; //?表示一个参数的占位符 //3.执行预编译sql语句(检查语法)
stmt = conn.prepareStatement(sql); //4.设置参数值
/**
* 参数一: 参数位置 从1开始
*/
stmt.setString(1, "李四");
stmt.setString(2, "男"); //5.发送参数,执行sql
int count = stmt.executeUpdate(); System.out.println("影响了"+count+"行"); } catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
JdbcUtil.close(conn, stmt);
}
} /**
* 修改
*/
@Test
public void testUpdate() {
Connection conn = null;
PreparedStatement stmt = null;
try {
//1.获取连接
conn = JdbcUtil.getConnection(); //2.准备预编译的sql
String sql = "UPDATE student SET NAME=? WHERE id=?"; //?表示一个参数的占位符 //3.执行预编译sql语句(检查语法)
stmt = conn.prepareStatement(sql); //4.设置参数值
/**
* 参数一: 参数位置 从1开始
*/
stmt.setString(1, "王五");
stmt.setInt(2, 9); //5.发送参数,执行sql
int count = stmt.executeUpdate(); System.out.println("影响了"+count+"行"); } catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
JdbcUtil.close(conn, stmt);
}
} /**
* 删除
*/
@Test
public void testDelete() {
Connection conn = null;
PreparedStatement stmt = null;
try {
//1.获取连接
conn = JdbcUtil.getConnection(); //2.准备预编译的sql
String sql = "DELETE FROM student WHERE id=?"; //?表示一个参数的占位符 //3.执行预编译sql语句(检查语法)
stmt = conn.prepareStatement(sql); //4.设置参数值
/**
* 参数一: 参数位置 从1开始
*/
stmt.setInt(1, 9); //5.发送参数,执行sql
int count = stmt.executeUpdate(); System.out.println("影响了"+count+"行"); } catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
JdbcUtil.close(conn, stmt);
}
} /**
* 查询
*/
@Test
public void testQuery() {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
//1.获取连接
conn = JdbcUtil.getConnection(); //2.准备预编译的sql
String sql = "SELECT * FROM student"; //3.预编译
stmt = conn.prepareStatement(sql); //4.执行sql
rs = stmt.executeQuery(); //5.遍历rs
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
String gender = rs.getString("gender");
System.out.println(id+","+name+","+gender);
} } catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
//关闭资源
JdbcUtil.close(conn,stmt,rs);
}
}
}

import com.loaderman.util.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement; import org.junit.Test; /**
* 模拟用户登录效果
* @author APPle
*
*/
public class Demo2 {
//模拟用户输入
//private String name = "ericdfdfdfddfd' OR 1=1 -- ";
private String name = "eric";
//private String password = "123456dfdfddfdf";
private String password = "123456"; /**
* Statment存在sql被注入的风险
*/
@Test
public void testByStatement(){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
//获取连接
conn = JdbcUtil.getConnection(); //创建Statment
stmt = conn.createStatement(); //准备sql
String sql = "SELECT * FROM users WHERE NAME='"+name+"' AND PASSWORD='"+password+"'"; //执行sql
rs = stmt.executeQuery(sql); if(rs.next()){
//登录成功
System.out.println("登录成功");
}else{
System.out.println("登录失败");
} } catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
JdbcUtil.close(conn, stmt ,rs);
} } /**
* PreparedStatement可以有效地防止sql被注入
*/
@Test
public void testByPreparedStatement(){
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
//获取连接
conn = JdbcUtil.getConnection(); String sql = "SELECT * FROM users WHERE NAME=? AND PASSWORD=?"; //预编译
stmt = conn.prepareStatement(sql); //设置参数
stmt.setString(1, name);
stmt.setString(2, password); //执行sql
rs = stmt.executeQuery(); if(rs.next()){
//登录成功
System.out.println("登录成功");
}else{
System.out.println("登录失败");
} } catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
JdbcUtil.close(conn, stmt ,rs);
} }
}
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties; /**
* jdbc工具类
* @author APPle
*
*/
public class JdbcUtil {
private static String url = null;
private static String user = null;
private static String password = null;
private static String driverClass = null; /**
* 静态代码块中(只加载一次)
*/
static{
try {
//读取db.properties文件
Properties props = new Properties();
/**
* . 代表java命令运行的目录
* 在java项目下,. java命令的运行目录从项目的根目录开始
* 在web项目下, . java命令的而运行目录从tomcat/bin目录开始
* 所以不能使用点.
*/
//FileInputStream in = new FileInputStream("./src/db.properties"); /**
* 使用类路径的读取方式
* / : 斜杠表示classpath的根目录
* 在java项目下,classpath的根目录从bin目录开始
* 在web项目下,classpath的根目录从WEB-INF/classes目录开始
*/
InputStream in = JdbcUtil.class.getResourceAsStream("/db.properties"); //加载文件
props.load(in);
//读取信息
url = props.getProperty("url");
user = props.getProperty("user");
password = props.getProperty("password");
driverClass = props.getProperty("driverClass"); //注册驱动程序
Class.forName(driverClass);
} catch (Exception e) {
e.printStackTrace();
System.out.println("驱程程序注册出错");
}
} /**
* 抽取获取连接对象的方法
*/
public static Connection getConnection(){
try {
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
} /**
* 释放资源的方法
*/
public static void close(Connection conn,Statement stmt){
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
} public static void close(Connection conn,Statement stmt,ResultSet rs){
if(rs!=null)
try {
rs.close();
} catch (SQLException e1) {
e1.printStackTrace();
throw new RuntimeException(e1);
}
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
}

db.properties

url=jdbc:mysql://localhost:3306/test
user=root
password=root
driverClass=com.mysql.jdbc.Driver

PreparedStatement执行sql語句的更多相关文章

  1. PreparedStatement執行sql語句

    import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import org ...

  2. PL/SQL Developer查詢已經執行過的SQL語句記錄 Ctrl+E

    PL/SQL Developer查詢已經執行過的SQL語句記錄 最近提数比较多,没有已存在的脚本信息,就手工写呀... 一次性打开了多个提数脚本文件,结果执行完后把脚本保存好了,但是最后的整理其它脚本 ...

  3. 使用预处理PreparedStatement执行Sql语句

    /** * 使用预处理的方式执行Sql * @param sql Sql语句 * @param obj 变量值数组 * @return 查询结果 * @throws SQLException */ p ...

  4. JDBC进阶之PreparedStatement执行SQL语句(MySQL)

    一.什么是PreparedStatement           参阅Java API文档,我们可以知道,PreparedStatement是Statement的子接口(如图所示),表示预编译的 SQ ...

  5. JDBC——PreparedStatement执行SQL的对象

    Statement的子接口,预编译SQL,动态SQL 功能比爹强大 用来解决SQL注入的 预编译SQL:参数使用?作为占位符,执行SQL的时候给?赋上值就可以了 使用步骤: 1.导入驱动jar包 复制 ...

  6. 使用PreparedStatement执行SQL语句时占位符(?)的用法

    1.Student数据库表 ID  name gender       2.Java代码 public static void main(String[] args) { int _id=1; Str ...

  7. 多條件查詢SQL語句

    表结构如下: –1.学生表 Student(s_id,s_name,s_birth,s_sex) –学生编号,学生姓名, 出生年月,学生性别 –2.课程表 Course(c_id,c_name,t_i ...

  8. 执行sql语句为什么?用PreparedStatement要比Statement好用

    PreparedStatement public interface PreparedStatement extends Statement;可以看到PreparedStatement是Stateme ...

  9. spring boot 框架根據 sql 創建語句自動生成 MVC層類代碼

    GITHUB: https://github.com/lin1270/spring_boot_sql2code 會自動生成model.mapper.service.controller. 代碼使用No ...

随机推荐

  1. IPC之shm.c源码解读

    // SPDX-License-Identifier: GPL-2.0 /* * linux/ipc/shm.c * Copyright (C) 1992, 1993 Krishna Balasubr ...

  2. NIM 1

    博弈论(一):Nim游戏 重点结论:对于一个Nim游戏的局面(a1,a2,...,an),它是P-position当且仅当a1^a2^...^an=0,其中^表示位异或(xor)运算. Nim游戏是博 ...

  3. java合并数组的几种方法,stream流合并数组

    一.实例代码 package cc.ash; import org.apache.commons.lang3.ArrayUtils; import java.lang.reflect.Array; i ...

  4. React组件:Dragact 0.1.4发布

    Dragact 是一款React组件,他能够使你简单.快速的构建出一款强大的 拖拽式网格(grid)布局. 仓库地址:Dragact 经过几天的迭代时间Dragact已经能够支持自由缩放功能了(res ...

  5. 一秒钟解决mysql使用游标出现取值乱码问题

    drop procedure if exists pro_test; delimiter // create procedure pro_test() begin declare str varcha ...

  6. python 中pip配置清华源

    anaconda配置镜像 Mac and Linux conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda ...

  7. SQL进程死锁排查

    --进程执行状态 SELECT der.[session_id],der.[blocking_session_id], sp.lastwaittype,sp.hostname,sp.program_n ...

  8. inner join和left join

    查询所有商品(product),包含他的所有的评论(comment),包含评论下的user 要使用 SELECT  * FROM product p LEFT JOIN COMMENT c ON p. ...

  9. input 唤起键盘后遮住页面元素

    var windheight = $(window).height(); /*未唤起键盘时当前窗口高度*/ $(window).resize(function(){ var docheight = $ ...

  10. MessagePack Java 0.6.X 动态类型

    我们知道 Java 是一个静态类型的语言.通过输入 Value MessagePack能够实现动态的特性. Value 有方法来检查自己的类型(isIntegerType(), isArrayType ...