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. 读书笔记《SpringBoot编程思想》

    目录 一. springboot总览 1.springboot特性 2.准备运行环境 二.理解独立的spring应用 1.应用类型 2.@RestController 3.官网创建springboot ...

  2. 【异常】Phoenix异常:java.lang.ArithmeticException: Rounding necessary

    1 异常sql upsert into WMBIGDATA.ODS_ES_CHARGING_STATION(id,evcosType,address,serviceTel,supportOrder,o ...

  3. main特别之处

    //package new_Object; public class Main{ public static void main(String[] args) { System.out.println ...

  4. spket IDE插件更新地址

    http://www.agpad.com/update spket  IDE插件更新地址

  5. NORDIC 修改MTU

    https://www.cnblogs.com/jiangjiu/p/10063556.html 注意要修改RAM起始地址,因为MTU增大了

  6. 【ios bug解决】 输入框聚焦时光标不显示

    解决办法:重写user-select样式 css:   user-select: text;-webkit-user-select:text;

  7. 51Nod 1714 1位数SG异或打表

    SG[i]表示一个数二进制下有i个1的SG值 SG[0]=0 打表: #include<bits/stdc++.h> using namespace std; ]; ]; , x; int ...

  8. 第二章 Vue快速入门--10-11 跑马灯效果制作

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8&quo ...

  9. shell的正则表达式

    正则表达式处理文件的内容,shell处理文件本身 grep *匹配0到n个 .(点儿)能匹配任意字符----8.8.8.8用于测试外网是否通畅 egrep

  10. 题解 【HEOI2016】tree树

    题面 解析 其实这题可以考虑离线做法,用并查集解决. 因为仔细想,添加标记并不方便, 但如果用并查集记录下祖先, 再一一删除,就会方便很多. 先把每次操作记录下来, 同时记录下每个点被标记的次数(因为 ...