感谢你的路过,希望学生的笔记能给你一点微不足道的参考 Java基础思维导图,完整Java体系的链接
一,概念
???Java DataBase Connectivity Java 数据库连接, Java语言操作数据库 ???Java具有坚固、安全、易于使用、易于理解和可从网络上自动下载等特性,是编写数据库应用程序的杰出言。所需要的只是 Java应用程序与各种不同数据库之间进行对话的方法。 ???JDBC可以在各种平台上使用Java,如Windows,Mac OS和各种版本的UNIX。 ???JDBC库包括通常与数据库使用相关的下面提到的每个任务的API。 - 连接数据库。 - 创建SQL或MySQL语句。 - 在数据库中执行SQL或MySQL查询。 - 查看和修改生成的记录。
二,JDBC体系结构
???JDBC API支持用于数据库访问的两层和三层处理模型,但通常,JDBC体系结构由两层组成: ??????- JDBC API:这提供了应用程序到JDBC管理器连接。 ??????- JDBC驱动程序API:这支持JDBC管理器到驱动程序连接。 ??????JDBC API使用驱动程序管理器和特定于数据库的驱动程序来提供与异构数据库的透明连接。
三,使用步骤:
???构建JDBC应用程序涉及以下六个步骤: ??????- 导入包:需要包含包含数据库编程所需的JDBC类的包。大多数情况下,使用import java.sql.*就足够 了。 ??????- 注册JDBC驱动程序:要求您初始化驱动程序,以便您可以打开与数据库的通信通道。 ??????- 打开连接:需要使用DriverManager.getConnection()方法创建一个Connection对象,该对象表 示与数据库的物理连接。 ??????- 执行查询:需要使用类型为Statement的对象来构建和提交SQL语句到数据库。 ??????- 从结果集中提取数据:需要使用相应的ResultSet.getXXX()方法从结果集中检索数据。 ??????- 释放资源:需要明确地关闭所有数据库资源,而不依赖于JVM的垃圾收集。
四,JDBC核心组件
DriverManager:驱动管理对象
功能:
1. 注册驱动:告诉程序该使用哪一个数据库驱动jar
注意:mysql5之后的驱动jar包可以省略注册驱动的步骤
2. 获取数据库连接:
* 方法:static Connection getConnection(String url, String user, String password)
* 参数:
* url:指定连接的路径
* 语法:jdbc:mysql://ip地址(域名):端口号/数据库名称
* 例子:jdbc:mysql://localhost:3306/db3
* 细节:如果连接的是本机mysql服务器,并且mysql服务默认端口是3306,则url可以简写为:jdbc:mysql:///数据库名称
* user:用户名
* password:密码
Driver:此接口处理与数据库服务器的通信,我们很少会直接与Driver对象进行交互。而是使DriverManager对象来管理这种类型的对象。
Connection:数据库连接对象
功能:
1. 获取执行sql 的对象
* Statement createStatement()
* PreparedStatement prepareStatement(String sql)
2. 管理事务:
* 开启事务:setAutoCommit(boolean autoCommit) :调用该方法设置参数为false,即开启事务
* 提交事务:commit()
* 回滚事务:rollback()
Statement:执行sql的对象(状态通道)
使用从此接口创建的对象将SQL语句提交到数据库。除了执行存储过程之外,一些派生接口还接受参数。
执行sql
1. boolean execute(String sql) :可以执行任意的sql 了解
2. int executeUpdate(String sql) :执行DML(insert、update、delete)语句、DDL(create,alter、drop)语句
* 返回值:影响的行数,可以通过这个影响的行数判断DML语句是否执行成功 返回值>0的则执行成功,反之,则失败。
3. ResultSet executeQuery(String sql) :执行DQL(select)语句
练习:
1. account表 添加一条记录
2. account表 修改记录
3. account表 删除一条记录
4,创建表
ResultSet:结果集对象,封装查询结果
* boolean next(): 游标向下移动一行,判断当前行是否是最后一行末尾(是否有数据),如果是,则返回false,如果不是则返回true
* getXxx(参数):获取数据
* Xxx:代表数据类型 如: int getInt() , String getString()
* 参数:
1. int:代表列的编号,从1开始 如: getString(1)
2. String:代表列名称。 如: getDouble("balance")
* 注意:
* 使用步骤:
1. 游标向下移动一行
2. 判断是否有数据
3. 获取数据
练习:
* 定义一个方法,查询emp表的数据将其封装为对象,然后装载集合,返回。
1. 定义em类
2. 定义方法 public List<em> findAll(){}
3. 实现方法 select * from em;
SQLException:此类处理数据库应用程序中发生的任何错误
代码: 再使用jdbc代码过程中会使用的jar包。
package com.wyh.CaoZuoBuZhou;
import java.sql.*;
public class Demo01_jdbc {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String userName = "root";
String passWord = "123654qw";
String url = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC";
connection = DriverManager.getConnection(url, userName, passWord);
statement = connection.createStatement();
String sql = "select * from student";
resultSet = statement.executeQuery(sql);
while(resultSet.next()){
System.out.println("姓名:"+resultSet.getString("stuname")+",电话:"+resultSet.getDouble("telphone"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (resultSet != null){ resultSet.close();}
if (statement != null){ statement.close();}
if (connection != null){connection.close();}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
五,多表操作
???四种:双向一对一,一对多,多对一, ???多对多 多表关系处理数据 ??????(1) 数据库通过外键建立两表关系 ??????(2) 实体类通过属性的方式建立两表关系 实体类要求:类名=表名,列名=属性名 代码:
package com.wyh.DuoBiaoGuanXi.dao;
import com.wyh.DuoBiaoGuanXi.bean.Student;
import com.wyh.DuoBiaoGuanXi.bean.Subject;
public interface SubjectDao {
public Student findById(int id);
public Subject findBySubId(int subId);
}
package com.wyh.DuoBiaoGuanXi.dao;
import com.wyh.DuoBiaoGuanXi.bean.Student;
import com.wyh.DuoBiaoGuanXi.bean.Teacher;
import java.util.List;
public interface TeacherDao {
public Teacher getById(int tid);
public List<Student> getAll();
}
package com.wyh.DuoBiaoGuanXi.dao;
import com.wyh.DuoBiaoGuanXi.bean.Husband;
import com.wyh.DuoBiaoGuanXi.bean.Wife;
public interface WifeDao {
public Wife getWife(int wid);
public Husband getHus(int hid);
}
package com.wyh.DuoBiaoGuanXi.dao.impl;
import com.wyh.DuoBiaoGuanXi.bean.Student;
import com.wyh.DuoBiaoGuanXi.bean.Subject;
import com.wyh.DuoBiaoGuanXi.dao.SubjectDao;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class SubjectDaoImpl implements SubjectDao {
@Override
public Student findById(int id) {
Connection connection =null;
PreparedStatement pps =null;
ResultSet resultSet =null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String userName="root";
String passWord="123654qw";
String url="jdbc:mysql://localhost:3306/jdbc_duobiaoguanxi?serverTimezone=UTC";
connection = DriverManager.getConnection(url, userName, passWord);
String sql="select * from student s,subject su,middle m where s.stuid=m.stuid and su.subid=m.subid and s.stuid=?";
pps = connection.prepareStatement(sql);
pps.setInt(1,id);
resultSet = pps.executeQuery();
Student student = new Student();
List<Subject> subjects=new ArrayList<>();
while (resultSet.next()){
student.setStuId(resultSet.getInt("stuid"));
student.setStuname(resultSet.getString("stuname"));
Subject subject = new Subject();
subject.setSubid(resultSet.getInt("subid"));
subject.setSubname(resultSet.getString("subname"));
subjects.add(subject);
}
student.setSubjects(subjects);
return student;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
try {
if (resultSet != null) {
resultSet.close();
}
if (pps != null) {
pps.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
return null;
}
@Override
public Subject findBySubId(int subId) {
Connection connection =null;
PreparedStatement pps =null;
ResultSet resultSet =null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String userName="root";
String passWord="123654qw";
String url="jdbc:mysql://localhost:3306/jdbc_duobiaoguanxi?serverTimezone=UTC";
connection = DriverManager.getConnection(url, userName, passWord);
String sql="select * from student s,subject su,middle m where s.stuid=m.stuid and su.subid=m.subid and su.subid=?";
pps = connection.prepareStatement(sql);
pps.setInt(1,subId);
resultSet = pps.executeQuery();
Subject subject = new Subject();
List<Student> studentList=new ArrayList<>();
while (resultSet.next()){
Student student = new Student();
student.setStuId(resultSet.getInt("stuid"));
student.setStuname(resultSet.getString("stuname"));
studentList.add(student);
subject.setSubid(resultSet.getInt("subid"));
subject.setSubname(resultSet.getString("subname"));
}
subject.setStudentList(studentList);
return subject;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
try {
if (resultSet != null) {
resultSet.close();
}
if (pps != null) {
pps.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
return null;
}
}
package com.wyh.DuoBiaoGuanXi.dao.impl;
import com.wyh.DuoBiaoGuanXi.bean.Student;
import com.wyh.DuoBiaoGuanXi.bean.Teacher;
import com.wyh.DuoBiaoGuanXi.dao.TeacherDao;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class TeacherDaoImpl implements TeacherDao {
@Override
public Teacher getById(int tid) {
Connection connection =null;
PreparedStatement pps =null;
ResultSet resultSet =null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String userName="root";
String passWord="123654qw";
String url="jdbc:mysql://localhost:3306/jdbc_duobiaoguanxi?serverTimezone=UTC";
connection = DriverManager.getConnection(url, userName, passWord);
String sql="select * from student s,teacher t where s.teacherid=t.tid and t.tid=?";
pps = connection.prepareStatement(sql);
pps.setInt(1,tid);
resultSet = pps.executeQuery();
Teacher teacher = new Teacher();
List<Student> students=new ArrayList<Student>();
while (resultSet.next()){
teacher.setTid(resultSet.getInt("tid"));
teacher.setTname(resultSet.getString("tname"));
Student student = new Student();
student.setStuid(resultSet.getInt("stuid"));
student.setStuname(resultSet.getString("stuname"));
students.add(student);
}
teacher.setStudents(students);
return teacher;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
try {
if (resultSet != null) {
resultSet.close();
}
if (pps != null) {
pps.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
return null;
}
@Override
public List<Student> getAll() {
Connection connection =null;
PreparedStatement pps =null;
ResultSet resultSet =null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String userName="root";
String passWord="123654qw";
String url="jdbc:mysql://localhost:3306/jdbc_duobiaoguanxi?serverTimezone=UTC";
connection = DriverManager.getConnection(url, userName, passWord);
String sql="select * from student s,teacher t where s.teacherid=t.tid";
pps = connection.prepareStatement(sql);
resultSet = pps.executeQuery();
resultSet = pps.executeQuery();
List<Student> students=new ArrayList<>();
while (resultSet.next()){
Student student = new Student();
student.setStuId(resultSet.getInt("stuid"));
student.setStuname(resultSet.getString("stuname"));
Teacher teacher = new Teacher();
teacher.setTid(resultSet.getInt("tid"));
teacher.setTname(resultSet.getString("tname"));
student.setTeacher(teacher);
students.add(student);
}
return students;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
try {
if (resultSet != null) {
resultSet.close();
}
if (pps != null) {
pps.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
return null;
}
}
package com.wyh.DuoBiaoGuanXi.dao.impl;
import com.wyh.DuoBiaoGuanXi.bean.Husband;
import com.wyh.DuoBiaoGuanXi.bean.Wife;
import com.wyh.DuoBiaoGuanXi.dao.WifeDao;
import java.sql.*;
public class WifeDaoImpl implements WifeDao {
@Override
public Wife getWife(int wid) {
Connection connection =null;
PreparedStatement pps =null;
ResultSet resultSet =null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String userName="root";
String passWord="123654qw";
String url="jdbc:mysql://localhost:3306/jdbc_duobiaoguanxi?serverTimezone=UTC";
connection = DriverManager.getConnection(url, userName, passWord);
String sql="select * from wife w,husband h where w.hid=h.husid and w.wifeid=?";
pps = connection.prepareStatement(sql);
pps.setInt(1,wid);
resultSet = pps.executeQuery();
Wife wife = new Wife();
while (resultSet.next()){
wife.setWifeid(resultSet.getInt("wifeid"));
wife.setWifeName(resultSet.getString("wifename"));
Husband husband = new Husband();
husband.setHusid(resultSet.getInt("husid"));
husband.setHusname(resultSet.getString("husname"));
wife.setHusband(husband);
}
return wife;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
try {
if (resultSet != null) {
resultSet.close();
}
if (pps != null) {
pps.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
return null;
}
@Override
public Husband getHus(int hid) {
Connection connection =null;
PreparedStatement pps =null;
ResultSet resultSet =null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String userName="root";
String passWord="123654qw";
String url="jdbc:mysql://localhost:3306/jdbc_duobiaoguanxi?serverTimezone=UTC";
connection = DriverManager.getConnection(url, userName, passWord);
String sql="select * from wife w,husband h where w.hid=h.husid and h.husid=?";
pps = connection.prepareStatement(sql);
pps.setInt(1,hid);
resultSet = pps.executeQuery();
Husband husband = new Husband();
while (resultSet.next()){
Wife wife = new Wife();
wife.setWifeid(resultSet.getInt("wifeid"));
wife.setWifeName(resultSet.getString("wifename"));
husband.setHusid(resultSet.getInt("husid"));
husband.setHusname(resultSet.getString("husname"));
husband.setWife(wife);
}
return husband;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
try {
if (resultSet != null) {
resultSet.close();
}
if (pps != null) {
pps.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
return null;
}
}
package com.wyh.DuoBiaoGuanXi;
import com.wyh.DuoBiaoGuanXi.bean.*;
import com.wyh.DuoBiaoGuanXi.dao.TeacherDao;
import com.wyh.DuoBiaoGuanXi.dao.impl.SubjectDaoImpl;
import com.wyh.DuoBiaoGuanXi.dao.impl.TeacherDaoImpl;
import com.wyh.DuoBiaoGuanXi.dao.impl.WifeDaoImpl;
import java.util.List;
public class Demo04 {
public static void main(String[] args) {
WifeDaoImpl wifeDao = new WifeDaoImpl();
Wife wife = wifeDao.getWife(1);
System.out.println(wife.getWifeName()+","+wife.getHusband().getHusname());
Husband hus = wifeDao.getHus(1);
System.out.println(hus.getHusname()+","+hus.getWife().getWifeName());
SubjectDaoImpl subjectDao = new SubjectDaoImpl();
Subject subject = subjectDao.findBySubId(2);
System.out.println(subject.getSubname());
List<Student> studentList = subject.getStudentList();
for (Student student : studentList) {
System.out.println("\t"+student.getStuname());
}
}
}
六,事务
1. 事务:一个包含多个步骤的业务操作。如果这个业务操作被事务管理,则这多个步骤要么同时成功,要么同时失败。
2. 操作:
1. 开启事务
2. 提交事务
3. 回滚事务
3. 使用Connection对象来管理事务
* 开启事务:setAutoCommit(boolean autoCommit) :调用该方法设置参数为false,即开启事务
* 在执行sql之前开启事务
* 提交事务:commit()
* 当所有sql都执行完提交事务
* 回滚事务:rollback()
* 在catch中回滚事务
4.Savepoints
设置保存点时,可以在事务中定义逻辑回滚点。如果通过保存点发生错误,则可以使用回滚方法来撤消 所有更改或仅保存在保存点之后所做的更改。 Connection对象有两种新的方法来帮助您管理保存点 - -
setSavepoint(String savepointName):定义新的保存点。它还返回一个Savepoint对象。 - releaseSavepoint(Savepoint savepointName):删除保存点。
请注意,它需要一个Savepoint 对象作为参数。此对象通常是由setSavepoint()方法生成的保存点。
案例:转账案例
代码:
package com.wyh.ShiWu;
import java.sql.*;
public class Demo05 {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
Savepoint abc = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String userName = "root";
String passWord = "123654qw";
String url = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC";
connection = DriverManager.getConnection(url, userName, passWord);
connection.setAutoCommit(false);
statement = connection.createStatement();
int resuet = statement.executeUpdate("insert into student(stuname,telphone,birthday) values('一三','1234568','1999-10-21')");
abc= connection.setSavepoint("abc");
int resuet2 = statement.executeUpdate("insert into student(stuname,telphone,birthday) values('二二','1234568','1999-10-21')");
System.out.println(5/0);
connection.commit();
if (resuet > 0) {
System.out.println("执行成功");
}else{
System.out.println("执行失败");
}
} catch (Exception e) {
e.printStackTrace();
try {
connection.rollback(abc);
connection.commit();
} catch (SQLException ex) {
ex.printStackTrace();
}
} finally {
try {
if (statement != null){ statement.close();}
if (connection != null){connection.close();}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
七,工具类
目的:就是为了然操作更加简单
属性文件
* 分析:
1. 注册驱动也抽取
2. 抽取一个方法获取连接对象
* 需求:不想传递参数(麻烦),还得保证工具类的通用性。
* 解决:配置文件
jdbc.properties
url=
user=
password=
方法:工具类中读取属性文件,使用ResourceBundle访问本地资源
代码:
package com.wyh.FengZhuangGongJuLei.dao;
import com.wyh.DuoBiaoGuanXi.bean.Student;
public interface Utildao {
public Student getByStuid(int id);
}
package com.wyh.FengZhuangGongJuLei.dao.impl;
import com.wyh.DuoBiaoGuanXi.bean.Student;
import com.wyh.FengZhuangGongJuLei.dao.Utildao;
import com.wyh.FengZhuangGongJuLei.util.DBUtils;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class UtildaoImpl extends DBUtils implements Utildao {
@Override
public Student getByStuid(int id) {
Student student = new Student();
try {
String sql = "select *from student where stuid=?";
List list = new ArrayList();
list.add(id);
ResultSet rs = query(sql,list);
while(rs.next()){
student.setStuId(rs.getInt("stuid"));
student.setStuname(rs.getString("stuname"));
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
closeAll();
}
return student;
}
}
package com.wyh.FengZhuangGongJuLei.util;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbcp.BasicDataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.List;
import java.util.Properties;
import java.util.ResourceBundle;
public class DBUtils {
private Connection connection;
private PreparedStatement pps;
private ResultSet resultSet;
private int count;
private static String dirverName;
private static String username;
private static String password;
private static String url;
private static BasicDataSource basicDataSource = new BasicDataSource();
private static ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
static {
}
protected Connection getConnection(){
try {
connection = comboPooledDataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
protected PreparedStatement getPps(String sql){
try {
pps = getConnection().prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return pps;
}
protected void param(List list){
if (list!=null&&list.size()>0){
for (int i = 0; i < list.size(); i++) {
try {
pps.setObject(i+1, list.get(i));
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
protected int update(String sql,List list){
getPps(sql);
param(list);
try {
count = pps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return count;
}
protected ResultSet query(String sql,List list){
getPps(sql);
param(list);
try {
resultSet = pps.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return resultSet;
}
protected void closeAll(){
try {
if (connection != null){
connection.close();
}
if(pps != null){
pps.close();
}
if(resultSet != null){
resultSet.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
package com.wyh.FengZhuangGongJuLei;
import com.wyh.DuoBiaoGuanXi.bean.Student;
import com.wyh.DuoBiaoGuanXi.bean.Wife;
import com.wyh.DuoBiaoGuanXi.dao.impl.TeacherDaoImpl;
import com.wyh.FengZhuangGongJuLei.dao.impl.UtildaoImpl;
public class Demo08_Util {
public static void main(String[] args) {
UtildaoImpl utildao = new UtildaoImpl();
Student student = utildao.getByStuid(1);
System.out.println(student.getStuid()+","+student.getStuname());
}
}
八,其他
???sql注入: ??????就是通过把SQL命令插入到Web表单提交或输入域名或页面请求的查询字符串,最终达到欺骗服务器执 行恶意的SQL命令。 代码:
package com.wyh;
import java.sql.*;
public class Demo02_jdbcsql {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String userName = "root";
String passWord = "123654qw";
String url = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC";
connection = DriverManager.getConnection(url, userName, passWord);
statement = connection.createStatement();
String username ="admin";
String password=" 'abc' or 1=1 ";
resultSet = statement.executeQuery("select * from student where stuname= '"+username+
"' and telphone = "+password);
while(resultSet.next()){
System.out.println("姓名:"+resultSet.getString("stuname")+",电话:"+resultSet.getDouble("telphone"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (resultSet != null){ resultSet.close();}
if (statement != null){ statement.close();}
if (connection != null){connection.close();}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
具体来说,它是利用现有应用程序,将(恶意的)SQL命令注入到后台数据库引擎 执行的能力,它可以通过在Web表单中输入(恶意)SQL语句得到一个存在安全漏洞的网站上的数据 库,而不是按照设计者意图去执行SQL语句。
PreparedStatement:执行sql的对象(预状态通道)
1. SQL注入问题:在拼接sql时,有一些sql的特殊关键字参与字符串的拼接。会造成安全性问题
1. 输入用户随便,输入密码:a' or 'a' = 'a
2. sql:select * from user where username = 'fhdsjkf' and password = 'a' or 'a' = 'a'
2. 解决sql注入问题:使用PreparedStatement对象来解决
3. 预编译的SQL:参数使用?作为占位符
4. 步骤:
1. 导入驱动jar包 mysql-connector-java-5.1.37-bin.jar
2. 注册驱动
3. 获取数据库连接对象 Connection
4. 定义sql
* 注意:sql的参数使用?作为占位符。 如:select * from user where username = ? and password = ?;
5. 获取执行sql语句的对象 PreparedStatement Connection.prepareStatement(String sql)
6. 给?赋值:
* 方法: setXxx(参数1,参数2)
* 参数1:?的位置编号 从1 开始
* 参数2:?的值
7. 执行sql,接受返回结果,不需要传递sql语句
8. 处理结果
9. 释放资源
5. 注意:后期都会使用PreparedStatement来完成增删改查的所有操作
1. 可以防止SQL注入
2. 效率更高
代码:
package com.wyh.CaoZuoBuZhou;
import java.sql.*;
public class Demo03_jdbc {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String userName = "root";
String passWord = "123654qw";
String url = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC";
connection = DriverManager.getConnection(url, userName, passWord);
String sql = "select * from student where stuname = ? and telphone = ?";
statement = connection.prepareStatement(sql);
String uname = "赵四";
String pass = "131333333";
statement.setString(1,uname);
statement.setString(2,pass);
resultSet = statement.executeQuery();
while(resultSet.next()){
System.out.println("姓名:"+resultSet.getString("stuname")+",电话:"+resultSet.getDouble("telphone"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (resultSet != null){ resultSet.close();}
if (statement != null){ statement.close();}
if (connection != null){connection.close();}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
JDBC批处理
定义:批量处理允许您将相关的SQL语句分组到批处理中,并通过对数据库的一次调用提交它们。 当您一次向数据库发送多个SQL语句时,可以减少连接数据库的开销,从而提高性能。
Statement批处理
- 使用createStatement()方法创建Statement对象。
- 使用setAutoCommit()将auto-commit设置为false 。
- 使用addBatch()方法在创建的语句对象上添加您喜欢的SQL语句到批处理中。
- 在创建的语句对象上使用executeBatch()方法执行所有SQL语句。
- 最后,使用commit()方法提交所有更改。
代码:
package com.wyh.PiLiangChuLi;
import java.sql.*;
public class Demo06_Statement {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
Savepoint abc = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String userName = "root";
String passWord = "123654qw";
String url = "jdbc:mysql://localhost:3306/jdbc_duobiaoguanxi?serverTimezone=UTC";
connection = DriverManager.getConnection(url, userName, passWord);
connection.setAutoCommit(false);
statement = connection.createStatement();
String sql1 = "insert into teacher(tname) values('张三a')";
statement.addBatch(sql1);
String sql2 = "insert into teacher(tname) values('张三b')";
statement.addBatch(sql2);
String sql3 = "insert into teacher(tname) values('张三c')";
statement.addBatch(sql3);
String sql4 = "insert into teacher(tname) values('张三d')";
statement.addBatch(sql4);
int[] ints = statement.executeBatch();
connection.commit();
for (int anint : ints){
System.out.println("anint="+anint);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
PreparedStatement批处理
1. 使用占位符创建SQL语句。
2. 使用prepareStatement() 方法创建PrepareStatement对象。
3. 使用setAutoCommit()将auto-commit设置为false 。
4. 使用addBatch()方法在创建的语句对象上添加您喜欢的SQL语句到批处理中。
5. 在创建的语句对象上使用executeBatch()方法执行所有SQL语句。
6. 最后,使用commit()方法提交所有更改。
反射处理结果集(反射这里我不熟悉,等等在看)
代码:
package com.wyh.PiLiangChuLi;
import java.sql.*;
public class Demo07_PreparedStatement {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement statement = null;
Savepoint abc = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String userName = "root";
String passWord = "123654qw";
String url = "jdbc:mysql://localhost:3306/jdbc_duobiaoguanxi?serverTimezone=UTC";
connection = DriverManager.getConnection(url, userName, passWord);
connection.setAutoCommit(false);
statement = connection.prepareStatement("insert into teacher(tname) values (?)");
statement.setString(1,"李四a");
statement.addBatch();
statement.setString(1,"李四b");
statement.addBatch();
statement.setString(1,"李四c");
statement.addBatch();
statement.setString(1,"李四d");
statement.addBatch();
int[] ints = statement.executeBatch();
connection.commit();
for (int anint : ints){
System.out.println("anint="+anint);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
九,连接池:
自定义连接池
数据连接池原理:
连接池基本的思想是在系统初始化的时候,将数据库连接作为对象存储在内存中,当用户需要访问数 据库时,并非建立一个新的连接,而是从连接池中取出一个已建立的空闲连接对象。使用完毕后,用户 也并非将连接关闭,而是将连接放回连接池中,以供下一个请求访问使用。而连接的建立、断开都由连 接池自身来管理。同时,还可以通过设置连接池的参数来控制连接池中的初始连接数、连接的上下限数 以及每个连接的最大使用次数、最大空闲时间等等,也可以通过其自身的管理机制来监视数据库连接的 数量、使用情况等。
实现思路:略
连接参数:
硬编码使用DBCP
Cp30:有问题
分析:估计是数据库驱动的问题,不用管。
* 步骤:
1. 导入jar包 (两个) c3p0-0.9.5.2.jar mchange-commons-java-0.2.12.jar ,
* 不要忘记导入数据库驱动jar包
2. 定义配置文件:
* 名称: c3p0.properties 或者 c3p0-config.xml
* 路径:直接将文件放在src目录下即可。
3. 创建核心对象 数据库连接池对象 ComboPooledDataSource
4. 获取连接: getConnection
代码:
//1.创建数据库连接池对象
DataSource ds = new ComboPooledDataSource();
//2. 获取连接对象
Connection conn = ds.getConnection();
Druid:
1. 导入jar包 druid-1.0.9.jar
2. 定义配置文件:
* 是properties形式的
* 可以叫任意名称,可以放在任意目录下
3. 加载配置文件。Properties
4. 获取数据库连接池对象:通过工厂来来获取 DruidDataSourceFactory
5. 获取连接:getConnection
DBCP:(省略)
练习(航空信息系统)
任务需求: 任务代码:
package com.wyh.rewu.bean;
import java.util.Date;
public class ls_xx_jdbc_rw {
private int id;
private String number;
private String address;
private Date begin;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getBegin() {
return begin;
}
public void setBegin(Date begin) {
this.begin = begin;
}
}
package com.wyh.rewu.dao;
import com.wyh.rewu.bean.ls_xx_jdbc_rw;
import java.util.Date;
import java.util.List;
public interface AirInfoDao {
public List<ls_xx_jdbc_rw> viewAll();
public List<ls_xx_jdbc_rw> getByDate(Date startDate);
public List<ls_xx_jdbc_rw> getByDestination(String destination);
public Boolean delete (int id);
public Boolean update(int id);
}
package com.wyh.rewu.dao.impl;
import com.wyh.rewu.bean.ls_xx_jdbc_rw;
import com.wyh.rewu.dao.AirInfoDao;
import com.wyh.rewu.util.DBUtils;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class AirInfoDaoImpl extends DBUtils implements AirInfoDao {
@Override
public List<ls_xx_jdbc_rw> viewAll() {
List<ls_xx_jdbc_rw> ls_xx_jdbc_rw1 = new ArrayList<>();
try {
String sql = "select * from ls_xx_jdbc_rw";
List list =new ArrayList();
ResultSet rs = query(sql,list);
while(rs.next()){
ls_xx_jdbc_rw ls_xx_jdbc_rw = new ls_xx_jdbc_rw();
ls_xx_jdbc_rw.setId(rs.getInt("id"));
ls_xx_jdbc_rw.setNumber(rs.getString("number"));
ls_xx_jdbc_rw.setAddress(rs.getString("address"));
ls_xx_jdbc_rw.setBegin(rs.getDate("begin"));
ls_xx_jdbc_rw1.add(ls_xx_jdbc_rw);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
closeAll();
}
return ls_xx_jdbc_rw1;
}
@Override
public List<ls_xx_jdbc_rw> getByDate(Date startDate) {
List<ls_xx_jdbc_rw> airInfoList = new ArrayList<>();
try {
String sql = "select * from ls_xx_jdbc_rw where begin=?";
List list = new ArrayList();
list.add(startDate);
ResultSet rs = query(sql, list);
while(rs.next()){
ls_xx_jdbc_rw airInfo = new ls_xx_jdbc_rw();
airInfo.setId(rs.getInt("id"));
airInfo.setNumber(rs.getString("number"));
airInfo.setAddress(rs.getString("address"));
airInfo.setBegin(rs.getDate("begin"));
airInfoList.add(airInfo);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
closeAll();
}
return airInfoList;
}
@Override
public List<ls_xx_jdbc_rw> getByDestination(String destination) {
List<ls_xx_jdbc_rw> ls_xx_jdbc_rwList2 = new ArrayList<>();
try {
String sql = "select * from ls_xx_jdbc_rw where address=?";
List list = new ArrayList();
list.add(destination);
ResultSet rs = query(sql, list);
while(rs.next()){
ls_xx_jdbc_rw ls_xx_jdbc_rw = new ls_xx_jdbc_rw();
ls_xx_jdbc_rw.setId(rs.getInt("id"));
ls_xx_jdbc_rw.setNumber(rs.getString("number"));
ls_xx_jdbc_rw.setAddress(rs.getString("address"));
ls_xx_jdbc_rw.setBegin(rs.getDate("begin"));
ls_xx_jdbc_rwList2.add(ls_xx_jdbc_rw);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
closeAll();
}
return ls_xx_jdbc_rwList2;
}
@Override
public Boolean delete(int id) {
String sql = "delete from ls_xx_jdbc_rw where id=?";
List list = new ArrayList();
list.add(id);
int count = update(sql,list);
if(count > 0){
return true;
}
return false;
}
@Override
public Boolean update(int id,List messageList) {
String sql = "update ls_xx_jdbc_rw set number=?,Address=?,Begin=? where id=?";
messageList.add(id);
int count = update(sql, messageList);
if (count > 0) {
return true;
}
return false;
}
@Override
public Boolean update(int id) {
String sql0= "select * from ls_xx_jdbc_rw where id=?";
ls_xx_jdbc_rw ls_xx_jdbc_rw = new ls_xx_jdbc_rw();
List list0 = new ArrayList();
list0.add(id);
ResultSet resultSet = query(sql0,list0);
try {
if(resultSet.next()) {
return true;
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return false;
}
}
package com.wyh.rewu.View;
import com.wyh.rewu.bean.ls_xx_jdbc_rw;
import org.jetbrains.annotations.NotNull;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
public class Ui {
private Scanner input = new Scanner(System.in);
public void welcome(){
System.out.println("==========欢迎使用航班信息管理系统==========");
}
public int functionSelect(){
System.out.println("请选择操作:1-查询所有航班,2-按起飞时间查询,3-按目的地查询,4-删除航班,5-更新航班,6-离开系统");
String str = input.nextLine();
int select = -1;
try {
select = Integer.parseInt(str);
} catch (NumberFormatException e) {
e.printStackTrace();
}
return select;
}
public void errorSelect(){
System.out.println("输入错误,请重新选择");
}
public void viewAll(List<ls_xx_jdbc_rw> list){
System.out.println("编号\t\t航班号\t\t目的地\t\t起飞日期");
for (ls_xx_jdbc_rw ls_xx_jdbc_rw : list) {
System.out.println(ls_xx_jdbc_rw.getId()+"\t\t"+
ls_xx_jdbc_rw.getNumber()+"\t\t"+ ls_xx_jdbc_rw.getAddress()+
"\t\t\t"+ ls_xx_jdbc_rw.getBegin());
}
}
public Date getDate(){
System.out.println("请输入要查询的日期:");
String str = input.nextLine();
java.util.Date date = null;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
date = format.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
java.sql.Date dayDateSql = new java.sql.Date(date.getTime());
return dayDateSql;
}
public String getDestination(){
System.out.println("请输入要查询的目的地:");
String str = input.nextLine();
return str;
}
public int getIdDelete(){
System.out.println("请输入要删除的航班的id:");
String str = input.nextLine();
int id = -1;
try {
id = Integer.parseInt(str);
} catch (NumberFormatException e) {
e.printStackTrace();
}
return id;
}
public int getIdUpdate(){
System.out.println("请输入要更新的航班的id");
String str = input.nextLine();
int id = -1;
try {
id = Integer.parseInt(str);
} catch (NumberFormatException e) {
e.printStackTrace();
}
return id;
}
public List messageList(){
List list = new ArrayList();
System.out.println("请输入新的航班号:");
list.add(input.nextLine());
System.out.println("请输入新的目的地:");
list.add(input.nextLine());
System.out.println("请输入新的起飞日期:");
list.add(input.nextLine());
return list;
}
public void success(){
System.out.println("操作成功");
}
public void fail(){
System.out.println("操作失败,请检查航班信息及网络状况");
}
public void bye(){
System.out.println("本次服务到此结束,祝您生活愉快!");
}
public void without(){
System.out.println("无此id对应的航班");
}
}
package com.wyh.rewu.util;
import com.alibaba.druid.pool.DruidDataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbcp.BasicDataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.ResourceBundle;
public abstract class DBUtils {
private Connection connection;
private PreparedStatement pps;
private ResultSet resultSet;
private int count;
private static String userName;
private static String userPass;
private static String url;
private static String driverName;
private static DruidDataSource dataSource = new DruidDataSource();
static {
ResourceBundle bundle = ResourceBundle.getBundle("db");
driverName = bundle.getString("driverclass");
url = bundle.getString("url");
userName = bundle.getString("uname");
userPass = bundle.getString("upass");
dataSource.setUsername(userName);
dataSource.setPassword(userPass);
dataSource.setUrl(url);
dataSource.setDriverClassName(driverName);
}
protected Connection getConnection(){
try {
connection = dataSource.getConnection();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return connection;
}
protected PreparedStatement getPps(String sql){
try {
pps = getConnection().prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return pps;
}
protected void param(List list){
if (list!=null&&list.size()>0){
for (int i = 0; i < list.size(); i++) {
try {
pps.setObject(i+1, list.get(i));
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
protected int update(String sql,List list){
getPps(sql);
param(list);
try {
count = pps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return count;
}
protected ResultSet query(String sql,List list){
getPps(sql);
param(list);
try {
resultSet = pps.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return resultSet;
}
protected void closeAll(){
try {
if (connection != null){
connection.close();
}
if(pps != null){
pps.close();
}
if(resultSet != null){
resultSet.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public abstract Boolean update(int id, List messageList);
}
package com.wyh.rewu;
import com.wyh.rewu.View.Ui;
import com.wyh.rewu.bean.ls_xx_jdbc_rw;
import com.wyh.rewu.dao.impl.AirInfoDaoImpl;
import java.util.Date;
import java.util.List;
public class AirInfoMain {
private static AirInfoDaoImpl airInfoDao = new AirInfoDaoImpl();
private static Ui ui = new Ui();
public static void main(String[] args) {
ui.welcome();
h:while(true){
switch (ui.functionSelect()){
case 1:// 查询所有航班
viewAll();
break ;
case 2:// 按起飞时间查询
queryByDate();
break ;
case 3:// 按目的地查询
queryByDestination();
break ;
case 4:// 删除航班
delete();
break ;
case 5:// 更新航班
update();
break ;
case 6:// 离开系统
break h;
default:
ui.errorSelect();
}
}
ui.bye();
}
private static void viewAll(){
List<ls_xx_jdbc_rw> list = airInfoDao.viewAll();
ui.viewAll(list);
}
private static void queryByDate(){
Date date = ui.getDate();
List<ls_xx_jdbc_rw> list = airInfoDao.getByDate(date);
ui.viewAll(list);
}
private static void queryByDestination(){
String destination = ui.getDestination();
List<ls_xx_jdbc_rw> list = (List<ls_xx_jdbc_rw>) airInfoDao.getByDestination(destination);
ui.viewAll(list);
}
private static void delete(){
int id = ui.getIdDelete();
if(airInfoDao.delete(id)){
ui.success();
}else {
ui.fail();
}
}
private static void update(){
int id = ui.getIdUpdate();
if(airInfoDao.update(id)) {
List list = ui.messageList();
if (airInfoDao.update(id, list)){
ui.success();
}else {
ui.fail();
}
}else {
ui.without();
}
}
}
package com.wyh.rewu;
import com.wyh.rewu.bean.ls_xx_jdbc_rw;
import com.wyh.rewu.dao.AirInfoDao;
import com.wyh.rewu.dao.impl.AirInfoDaoImpl;
import java.util.ArrayList;
import java.util.List;
public class task {
public static void main(String[] args) {
AirInfoDao airInfoDao =new AirInfoDaoImpl();
List<ls_xx_jdbc_rw> airInfoList = new ArrayList<ls_xx_jdbc_rw>();
airInfoList = airInfoDao.viewAll();
for (ls_xx_jdbc_rw airInfo : airInfoList) {
System.out.println("编号:"+ airInfo.getId()+"\t航班号"+ airInfo.getNumber()+"\t目的地"+ airInfo.getAddress()+"\t起飞时间"+ airInfo.getBegin());
}
}
}
附录(jdbc的成长演化):
参考:距离记笔记的时候过了一段时间,如果我的笔记有明显借鉴了您的内容,请见谅。(我记忆力很差的,当初写笔记的时候,参考文档记录的可能不全) 资料下载链接(笔记+代码+其他):百度网盘 链接:https://pan.baidu.com/s/1TT7JaNb3vJPhUf3P83mo2w 提取码:1111 感谢阅读,祝你从此一帆风顺。
|