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. Samba编码设置方法

    弟管理學校的網頁伺服器,該伺服器也同時是大家的分享檔案集散中心,是以Linux架設起來的,該伺服器以 Unicode 作為系統編碼,而其他Windows系統則是big5(MS950)編碼,最近我要讓另 ...

  2. 第十一章· MHA高可用及读写分离

    一.MHA简介 1.1.作者简介 松信嘉範: MySQL/Linux专家 2001年索尼公司入职 2001年开始使用oracle 2004年开始使用MySQL 2006年9月-2010年8月MySQL ...

  3. ubuntu安装软件apt-get

    一. apt-get用法 apt 0.8.16~exp12ubuntu10.26 for i386 compiled on Aug  5 2015 19:06:21Usage: apt-get [op ...

  4. sql语句 小记录

    select Name '姓名',Age '年龄',(select LessonName + ',' from Lesson where StudentId=s1.Id FOR XML PATH('' ...

  5. 【转】关于 Error[Pe020]: identifier "HAL_StatusTypeDef" is undefined

    @2019-06-06 [小记] 这个bug比较常见,右键可以定位到相关头文件,但系统依旧报错,其实主要还是头文件的问题. 1.需要检查头文件中关于主程序所用到的部分是否已经使能,尤其是 “stm32 ...

  6. linux 命令技巧(转)--history

    本文介绍一些关于bash的能够提高效率的技巧,主要是关于历史命令操作和一些快捷键,让你在命令行下工作效率翻倍. 1.history-----最基本的查看历史命令 2.!n-----编号为n的历史命令 ...

  7. Android异常与性能优化相关面试问题-内存管理面试问题详解

    内存管理机制概述: 分配机制:操作系统会为每一个进程分配一个合理的内存大小,从而保证每一个进程能够正常的运行,不至于内存不够使用,或者某个进程占用过多的内存. 回收机制:在系统内存不足的时候,系统有一 ...

  8. python 示例代码3

    示例3:Python获取当前环境下默认编码(字符编码demo1.py) 字符编码,python解释器在加载py文件中的代码时,会对内容进行编码(默认ASCII),windows系统默认编码为GBK,U ...

  9. slices = [dicom.read_file(path + '/' + s) for s in os.listdir(path)] FileNotFoundError: [WinError 3] 系统找不到指定的路径。

    最近跟着kaggle做一个医疗项目,加载路径总是出错. 将下面箭头处: 改为: path = os.path.join(data_dir, patient)问题迎刃而解 上面的路径拼接方法可能是ipy ...

  10. UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd0 in position 0: invalid continuation byte

    用pandas打开csv文件可能会出现这种情况,原因可能是excel自己新建一个*.csv文件时候容易出错.进入文件另存为,然后选择csv文件即可.