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. dhcpd.conf配置文件几例

    例1   ddns-update-style interim; ignore client-updates; subnet 192.168.222.0 netmask 255.255.255.0 { ...

  2. c++ mfc和win32项目

    win32项目是一个底层的窗口的实现过程,它采用的库仅仅是windows.h,我们通过winain作为函数的入口,然后经过窗口类的内容的填写,窗口的注册,创建,显示刷新,到最后的消息循环,这是一个wi ...

  3. 下拉菜单 Spinner 简单纯字符串版

    下拉菜单 Spinner 简单纯字符串版 public class MainActivity extends Activity implements AdapterView.OnItemSelecte ...

  4. netty-2.客户端与服务端互发消息

    (原) 第二篇,客户端与服务端互发消息 与第一篇的例子类似,这里服务端需要三个类,客户端也需要三个类. 服务端关键代码如下:MyServer与上一个例子中的TestServer 差多,这里只列举不同的 ...

  5. linux抓取usb包设置usbmon

  6. 怎么卸载hexo

    npm uninstall hexo -g 卸载失败 npm uninstall hexo-cli -g 推荐这个,成功卸载

  7. JAVA 日期操作

    1.用java.util.Calender来实现 Calendar calendar=Calendar.getInstance(); calendar.setTime(new Date()); Sys ...

  8. CSS3—HSL与HSLA属性

    ㈠HSL(H,S,L) ⑴通过对色相(H).饱和度(S).明度(L)三个颜色通道的变化以及它们相互之间的叠加来得到各式各样的颜色 ⑵取值 H:Hue(色调).0(或360)表示红色,120表示绿色,2 ...

  9. JVM(一),谈谈你对java的理解

    一.谈谈你对java的理解 1.Java特性 (1)平台无关性 一次编译到处运行 (2)GC 垃圾回收机制 (3)语言特性 泛型-反射机制-lambda表达式 (4)面向对象 面向对象语言-三大特性( ...

  10. html css回顾总结

    //html基本结构<!DOCTYPE html> <html lang="en"> <head> <meta charset=" ...