JDBC
一、JDBC环境搭建
Idea
1.左上文件==新建==项目==左侧新建项目==输入JDBC==构建系统选择IDEA==点击创建
2.选中项目名JDBC==右键新建==目录==输入lib==回车
3.复制mysql-connector-java-5.1.37.jar包==对着lib粘贴==点击确定
4.选中lib文件夹==右键添加为库==点击确定
5.对着src==右键新建==软件包==com.tys.JDBC
6.对着com.tys.JDBC==右键新建==Java类==TestJDBC
7.打开SQLyog,并且确认companydb数据库存在
8.复制增删改代码,右键运行即可
二、JDBC开发步骤
package com.tys.JDBC;
import java.sql.*;
public class TestJDBC {
public static void main(String[] args) throws Exception {
//1.注册驱动,加载驱动
Class.forName("com.mysql.jdbc.Driver") ;
//2.获得数据库连接
String url="jdbc:mysql://localhost:3306/companydb?useUnicode=true&characterEncoding=utf-8&useSSL=false"; //连接到哪个数据库
String user="root";
String password="123456";
Connection connection=DriverManager.getConnection(url,user,password);
if(connection!=null){
System.out.println("连接到数据库了");
}else{
System.out.println("连接失败");
}
//3.获得执行SQL语句的对象(使用Statement类)
Statement statement=connection.createStatement();
//4.编写SQL语句 执行SQL语句
String sql="INSERT INTO t_jobs(job_id,JOB_TITLE,MIN_SALARY,MAX_SALARY) VALUES ('H5_Mgr','H5_Manager',4000,10000)";
int result=statement.executeUpdate(sql); //返回受影响的行数
//5.处理数据库的返回结果
if(result==1) {
//返回受影响的行数
System.out.println("创建成功");
}else{
System.out.println("创建失败");
}
//6.关闭资源
statement.close();
connection.close();
}
}
三、SQL注入
SQL注入问题:
用户输入的数据中有SQL关键字或语法并且参与了SQL语句的编译,导致SQL语句编译后的条件含义为true,一直得到正确的结果,这种现象称为SQL注入。
PreparedStatement(修复SQL注入):
由于编写的SQL语句是在用户输入数据,整合后再进行编译,所以为了避免SQL注入的问题,我们要使SQL语句在用户输入数据前就已进行编译成完整的SQL语句,再进行填充数据
#创建用户表users
#插入两条测试语句
CREATE TABLE users(
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(20) UNIQUE NOT NULL,
pwd VARCHAR(20) NOT NULL,
phone VARCHAR(11)
)CHARSET=utf8;
INSERT INTO users(username,pwd,phone) VALUES ('zhangsan','1234','4008100100');
INSERT INTO users(username,pwd,phone) VALUES ('lisi','1234','4008120120');
package com.tys.JDBC;
import java.sql.*;
import java.util.*;
public class TestJDBC {
public static void main(String[] args) throws Exception{
Scanner scanner=new Scanner(System.in);
System.out.println("请输入用户名:");
String username= scanner.nextLine(); //改成nextLine 可以接受空格
System.out.println("请输入密码:");
String password= scanner.nextLine(); //abc' or 1=1;#
//1.注册驱动,加载驱动
Class.forName("com.mysql.jdbc.Driver") ;
//2.获得数据库连接
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/companydb?useUnicode=true&characterEncoding=utf-8&useSSL=false","root","123456");
//3.获得PreparedStatement的对象
PreparedStatement preparedStatement=connection.prepareStatement("select * from users where username=? and pwd=?");
//4.为?占位符进行赋值
preparedStatement.setString(1,username); //下标从1开始
preparedStatement.setString(2,password);
//5.编写SQL语句 执行SQL语句
ResultSet resultSet=preparedStatement.executeQuery();
//6.处理数据库的返回结果
if(resultSet.next()) {
//查询到数据
System.out.println("登陆成功");
}else {
System.out.println("登陆失败");
}
//7.关闭资源
resultSet.close();
preparedStatement.close();
connection.close();
}
}
四、封装工具类与ORM
DBUtils工具类:
在实际JDBC开发中,存在大量重复代码,我们把传统的JDBC代码进行重构,抽取出通用的JDBC工具类,以后连接任何数据库,释放资源都可以使用这个工具类
ORM封装零散数据:
从数据库查询到的结果集(ResultSet)在进行遍历时,逐行遍历。取出的都是零散的数据,在实际应用开发中,我们需要将零散的数据进行封装整理
实体类:是零散数据的载体
- 一行数据中,多个零散的数据进行整理
- 通过entity的规则对表中的数据进行对象的封装
- 表名=类名,列名=属性名,提供各个属性的get set方法
- 提供无参构造方法,视情况添加有参构造
五、DBUtils工具类
package com.tys.utils;
import java.sql.*;
public class DBUtils {
private static ThreadLocal<Connection> threadLocal=new ThreadLocal<>();
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String url = "jdbc:mysql://localhost:3306/university_graduatedb?useUnicode=true&characterEncoding=utf-8&useSSL=false";
static final String user = "root";
static final String password = "123456";
//获得连接
public static Connection getConnection() {
Connection connection = threadLocal.get();//将当前线程中绑定的connection对象赋值给connection
try {
Class.forName(JDBC_DRIVER);
if (connection==null){
connection =DriverManager.getConnection(url, user, password);
threadLocal.set(connection);//把连接存在当前线程共享中
}
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
//开启事务
public static void begin(){
try {
Connection connection=getConnection();
connection.setAutoCommit(false);
}catch (SQLException e){
e.printStackTrace();
}
}
//提交事务
public static void commit(){
Connection connection=null;
try {
connection=getConnection();
connection.commit();
}catch (SQLException e){
e.printStackTrace();
}finally {
closeAll(connection,null,null);
}
}
//回滚事务
public static void rollback(){
Connection connection=null;
try {
connection=getConnection();
connection.rollback();
}catch (SQLException e){
e.printStackTrace();
}finally {
closeAll(connection,null,null);
}
}
//关闭连接,释放资源
public static void closeAll(Connection connection,Statement statement,ResultSet resultSet) {
try{
if (resultSet!=null){
resultSet.close();
}
if (statement!=null){
statement.close();
}
if (connection!=null){
connection.close();
threadLocal.remove();//关闭连接后,移除已关闭connection对象
}
}catch (SQLException e){
e.printStackTrace();
}
}
}
六、DAO层增删改查
//新增 管理员主页,添加学生账户的实现
import java.sql.*;
public int addStudent(Student student) throws SQLException {
Connection conn= DBUtils.getConnection();
String sql="insert into account_student(stuname,password,studentId) values (?,?,?)";
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1, student.getStuname());
ps.setString(2, student.getPassword());
ps.setString(3, student.getStudentId());
int rs=ps1.executeUpdate();
if(rs==1) {
DBUtils.closeAll(conn,ps,null);
return 1;
}else {
DBUtils.closeAll(conn,ps,null);
return 0;
}
}
======================================================================================
//修改 教师列表,点击编辑按钮
import java.sql.*;
public int EditTeacher(Teacher teacher) throws SQLException {
String sql="update teacherinfo set tname=?,tdept=?,tel=? where teacherId=?";
Connection conn= DBUtils.getConnection();
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1, teacher.getTname());
ps.setString(2, teacher.getTdept());
ps.setString(3, teacher.getTel());
ps.setString(4, teacher.getTeacherId());
int rs=ps.executeUpdate();
if(rs==1) {
DBUtils.closeAll(conn,ps,null);
return 1;
}else {
DBUtils.closeAll(conn,ps,null);
return 0;
}
}
======================================================================================
//删除 教师列表,点击删除按钮
import java.sql.*;
public int deleteTeacher(String teacherId) throws SQLException {
Connection conn= DBUtils.getConnection();
String sql="delete from teacherinfo where teacherId=?";
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1, teacherId)