DriverManager
●DriverManager(驱动管理类)作用:
1.注册驱动
2.获取数据库连接
Connection
●Connection(数据库连接对象)作用:
1.获取执行SQL的对象
2.管理事务
import java.sql.*;
public class transaction {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn= DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test","root","123456");
String sql1="update offer set money=money+500 where Name='张三'";
String sql2="update offer set money=money-500 where Name='李四'";
Statement sta=conn.createStatement();
try {
conn.setAutoCommit(false);
int count1=sta.executeUpdate(sql1);
System.out.println("当前受影响的行:"+count1);
int count2=sta.executeUpdate(sql2);
System.out.println("当前受影响的行:"+count2);
conn.commit();
} catch (SQLException throwables) {
conn.rollback();
throwables.printStackTrace();
}
sta.close();
conn.close();
}
}
Statement
●Statement作用:
1.执行SQL语句
ResultSet
●ResultSet(结果集对象)作用:
1.封装了DQL查询语句的结果
●使用步骤:
●ResultSet案例:
需求:查询account账户表数据,封装为Account对象中,并且存储到ArrayList集合中
PreparedStatement
●PreparedStatement作用:
1.预编译SQL语句并执行:预防SQL注入问题
●SQL注入
➠SQL注入是通过操作输入来修改事先定义好的SQL语句,用以达到执行代码对服务器进行攻击的方法。
eg:(某登录页面用户名随便填写,密码写一段特殊的脚本便可登录成功。这样的系统非常不安全,登录后可进行攻击,可在系统里为所欲为)
import java.sql.*;
import java.util.Scanner;
public class JDBCdemo {
public static void main(String[] args) throws Exception {
//1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.获取连接
Connection conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test","root","123456");
//3.接受用户输入
Scanner in=new Scanner(System.in);
System.out.println("请输入用户名");
String name=in.next();
System.out.println("请输入密码");
String password=in.next();
String sql="select * from user where u_name=? and u_password=?";
//4.获取Statement对象
PreparedStatement sta=conn.prepareStatement(sql);
sta.setString(1,name);
sta.setString(2,password);
//5.执行SQL获取ResultSet 对象结果集
ResultSet re=sta.executeQuery();
if(re.next()){
System.out.println("登录成功");
}else{
System.out.println("登录失败");
}
re.close();
sta.close();
conn.close();
}
}
如何解决SQL注入问题?:(通过PreparedStatement对象来解决)
➠PreparedStatement原理