对比statement和preparedstatement
statement存在SQL注入问题,preparedstatement解决了SQL注入问题。
statement:存在SQL注入现象,编译一次执行一次。
preparedstatement:解决了SQL注入问题,编译一次,可执行N次,且效率更高。
preparedstatement会在编译阶段做类型的安全检查
需要SQL注入情况
由上可知,大多数情况下,使用的均是preparedstatement,但是会存在极少数的情况需要使用statement。但凡业务需求中需要进行SQL注入或者需要进行SQL语句拼接时,则需要使用statement。
/*
* 需要SQL注入的情况
* */
import java.sql.*;
import java.util.Map;
import java.util.Scanner;
public class Demo03 {
public static void main(String[] args) {
//用户在控制台输入desc就是降序,输入asc就是升序
Scanner s = new Scanner(System.in);
System.out.println("输入desc就是降序,输入asc就是升序");
System.out.println("请输入:");
String keyWords = s.nextLine();
//执行SQL
Connection conn = null;
Statement stmt = null;
ResultSet rs =null;
try {
//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","333");
//3.获取数据库操作对象
stmt = conn.createStatement();
//4.执行SQL
String sql = "select ename from emp order by ename "+keyWords;
rs= stmt.executeQuery(sql);
//5.遍历查询结果
while (rs.next()){
System.out.println(rs.getString("ename"));
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (rs != null){
try {
rs.close();
}catch (SQLException e){
e.printStackTrace();
}
}
if (stmt != null){
try {
stmt.close();
}catch (SQLException e){
e.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
}catch (SQLException e){
e.printStackTrace();
}
}
}
}
}
JDBC完成增删改任务
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/*
* JDBC 完成增删改
*
* */
public class Demo04 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps =null;
try {
//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接
// conn = DriverManager.getConnection("jdbc:mysql//localhost:3306/bjpowernode","root","333");注意URL的书写格式
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","333");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","333");
//3.获取数据库操作对象,写SQL语句
//增
// String sql = "insert into dept (deptno,dname,loc) values(?,?,?)";
// ps = conn.prepareStatement(sql);
// ps.setInt(1,70);
// ps.setString(2,"销售部");
// ps.setString(3,"西安");
//改
// String sql = "update dept set dname= ?,loc = ? where deptno = ?";
// ps = conn.prepareStatement(sql);
// ps.setString(1,"研发一部");
// ps.setString(2,"汉中");
// ps.setInt(3,60);
//删
String sql = "delete from dept where deptno = ?";
ps = conn.prepareStatement(sql);
ps.setInt(1,70);
//4.执行SQL语句
int count = ps.executeUpdate();
System.out.println(count);
//5.遍历查询结果集
// while ()
} catch (Exception e) {
e.printStackTrace();
}finally {
if (ps !=null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}if(conn !=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}