一:什么是jdbc
Java数据库连接,(Java Database Connectivity,简称JDBC)是Java语言中用来规范客户端程序如何来访问数据库的应用程序接口,提供了诸如查询和更新数据库中数据的方法,我们通常说的JDBC是面向关系型数据库的。
二.jdbc的基本步骤
1.加载驱动(选择数据库)
2.获取连接(与数据库建立连接)
3.编写SQL语句
4.构建处理块(封装发送SQL)
5.发送SQL,得到结果
6.处理结果
7.连接关闭
三:jdbc增删改查操作
1.insert操作实例
public class Demo3_insert {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
//注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//建立连接
String url="jdbc:mysql://localhost:3306/database_user";
String root="root";
String password="13177936413qq";
Connection con= DriverManager.getConnection(url,root,password);
//编写sql语句
System.out.println("请输入编号:");
int id=scanner.nextInt();
System.out.println("请输入性别:");
String sex=scanner.next();
System.out.println("请输入姓名:");
String name=scanner.next();
System.out.println("请输入英语成绩:");
int english=scanner.nextInt();
System.out.println("请输入数学成绩:");
int math=scanner.nextInt();
System.out.println("请输入语文成绩:");
int chinese=scanner.nextInt();
String sql="insert into student_info values ("+id+",'"+sex+"','"+name+"',"+english+","+math+","+chinese+")";
PreparedStatement st=con.prepareStatement(sql);
int n=st.executeUpdate();
System.out.println(n>0?"添加信息成功!":"添加信息失败");
//关闭连接
//1.关闭流是从小到大顺序进行
//2.判空
if (st!=null&&!st.isClosed()) {
st.close();
}
if (con!=null&&!con.isClosed()) {
con.close();
}
}
}
2.delete操作
public class Demo6_delete {
public static void main(String[] args) throws Exception {
Scanner scanner=new Scanner(System.in);
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/database_user";
String user="root";
String password="13177936413qq";
Connection con= DriverManager.getConnection(url,user,password);
//编写sql语句
String sql="delete from student_info where id=?";
System.out.println("请输入要删除信息所在id:");
int id=scanner.nextInt();
//创建prepareedstatement对象
PreparedStatement st=con.prepareStatement(sql);
//填充
st.setInt(1,id);
int n=st.executeUpdate();
System.out.println(n>0?"删除成功!":"删除失败!");
//关闭流
if (st!=null&&!st.isClosed()){
st.close();
}
if (con!=null&&!con.isClosed()){
con.close();
}
}
}
3.update操作
public class Demo5_update {
public static void main(String[] args) throws Exception {
Scanner scanner=new Scanner(System.in);
//注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/database_user";
String user="root";
String password="13177936413qq";
//建立连接
Connection con= DriverManager.getConnection(url,user,password);
System.out.println("请输入id:");
int id=scanner.nextInt();
System.out.println("请输入要修改的性别:");
String sex=scanner.next();
System.out.println("请输入要修改的姓名:");
String name=scanner.next();
System.out.println("请输入要修改的英语成绩");
int english=scanner.nextInt();
System.out.println("请输入要修改的数学成绩");
int math=scanner.nextInt();
System.out.println("请输入要修改的语文成绩");
int chinese=scanner.nextInt();
//编写sql语句
String sql="UPDATE student_info set sex=?,name=?,english=?,math=?, chinese=? where id=?";
//填充数据
PreparedStatement st=con.prepareStatement(sql);
st.setString(1,sex);
st.setString(2,name);
st.setInt(3,english);
st.setInt(4,math);
st.setInt(5,chinese);
st.setInt(6,id);
int n= st.executeUpdate();
System.out.println(n>0? "执行成功":"执行失败");
//关闭流
if (st!=null&&!st.isClosed()){
st.close();
}
if (con!=null&&!con.isClosed()){
con.close();
}
}
}
4.select操作 查询操作(根据id的值查询)
public class Demo1_query1 {
public static void main(String[] args) throws Exception {
//注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/database_user";
String user="root";
String password="13177936413qq";
//建立连接
Connection con=DriverManager.getConnection(url,user,password);
//
Statement statement=con.createStatement();
//定义sql语句
String sql="SELECT * from student_info";
//执行sql语句
ResultSet res=statement.executeQuery(sql);
while(res.next()){
System.out.println("-------------");
System.out.print("id:"+res.getInt("id")+" ");
System.out.print("sex:"+res.getString("sex")+" ");
System.out.print("name:"+res.getString("name")+" ");
System.out.print("english:"+res.getInt("english")+" ");
System.out.print("math:"+res.getInt("math")+" ");
System.out.println("chinese:"+res.getInt("chinese"));
System.out.println();
}
//关闭流
res.close();
statement.close();
con.close();
}
}
5.select操作 查询操作(查询所有信息)
public class Demo2_query2 {
public static void main(String[] args) throws Exception {
Scanner scanner=new Scanner(System.in);
//1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.建立连接
String url = "jdbc:mysql://localhost:3306/database_user";
String user="root";
String password="13177936413qq";
Connection connection = DriverManager.getConnection(url,user,password);
//3.编写sql语句
System.out.println("请输入id:");
int id=scanner.nextInt();
String sql="SELECT * from student_info where id="+id+"";
// 4.将sql语句交给数据库,即加载sql语句
Statement statement = connection.createStatement();
//5.执行sql语句有两种
ResultSet re=statement.executeQuery(sql);
// 1.updatequerie
//2.executupdate 通常用于insert delete语句返回的是int类型的值
//表示的是受影响的行数
while(re.next()){
//拿出相应的字段
String sex=re.getString("sex");
String name=re.getString("name");
int english=re.getInt("english");
int math=re.getInt("math");
int chinese=re.getInt("chinese");
//打印
System.out.print(sex+" "+name+" "+english+" "+math+" "+chinese);
}
}
}
四:jdbc的核心接口
java.sql.DriverManager类驱动管理器
java.sql.Connection接口数据库连接
java.sql.Statement接口 sql指今的"加载执行器"
java.sqL.ResultSet接口 结果集
4.1 DriverManager类
1.注册驱动
在Driver类中的静态初始化块中,注册驱动:DriverManager.registerDriver(new Driver ());
Class. forName (" com.mysql.ci.jdbc.Driver)
在我们的应用程序中手动注册驱动的代码也可以省略Class.forName("com.mysql.cj.jdbc.Driver");
/如果我们没有手动汪册驱动,驱动管理器在获取连接的时候发现没有汪册驱动则读取 驱动jar/META-
INF/servicesjava sql.Driver文件中配器的驱动类路径进行注册
2.连接数据库
1.url 数据库服务器的地址
2.username 数据库连接用户名
3.password 数据库连接密码
Connection connection = DriverManager.getConnection(url,"root". "123456");
4.2 Connection接口
1.Statment createStatement();创建Statement对象
2.PrepareStatement prepareStatement(Sting sql);创建PrepareStatement对象
3.CallableStatement prepareCall(String sql);创建prepareCall对象
4.3.Statement接口:执行静态sql语句。
int executeUpdate(String sql):执行静态的更新sql语句(DDL,DML 增加,修改,删除操作)
ResultSet executeQuery(String sql):执行静态的查询sql语句(DQL 查询操作)
4.4.PreparedStatement接口:用于执行预编译sql语句
int executeUpdate(String sql);执行预编译的更新sql语句(DDL,DML)
ResultSet executeQuery();执行预编译的查询sql语句(DQL)
预编译是指我们的sql语句所执行的sql语句参数是未知的,此时无法编译,因此被称为预编译
4.5 CallableStatement接口:
ResultSet executeQuery();调用储存过程的方法
4.6ResultSet接口:用于封装查询出啦的数据
boolean next ()将光标移动到下一行,其实就相当于一个指针的作用,当其指针指到下一行数据时存在值时,就返回为true
getXX()获取列的值
五.sql注入问题
SQL注入是指在编程中SQL语句中参数可以通过客户端传递到数据库中执行,由于对传递内容过滤不严谨,导致SQL执行出现非预期结果
一般情况下,我们为了防止此类失误,采用PreparedStatement接口解决安全问题,他是statement的子接口
六.工具类的封装
package com.jdbc.demo.utils;
import java.sql.*;
public class DBhelper {
//将其设置为常量属性,便于管理
private static final String Driver = "com.mysql.cj.jdbc.Driver";
private static final String url = "jdbc:mysql://localhost:3306/database_user";
private static final String user = "root";
private static final String password = "13177936413qq";
static{
try {
Class.forName(Driver);
} catch (ClassNotFoundException e) {
System.out.println("加载驱动失败!");
throw new RuntimeException(e);
}
}
public static Connection getConnection(){
Connection connection=null;
//直接获取连接即可
try {
connection = DriverManager.getConnection(url,user,password);
} catch (SQLException e) {
System.out.println("数据库连接失败!");
throw new RuntimeException(e);
}
return connection;
}
//1.查询操作
public static void close(ResultSet resultSet,Statement st, Connection connection) throws SQLException {
if (resultSet==null&&!resultSet.isClosed()){
resultSet.close();
}
if (st == null&&!st.isClosed()){
st.close();
}
if (connection == null&&!connection.isClosed()){
connection.close();
}
}
//3.增加操作,修改操作
public static void close(Statement st,Connection connection) throws SQLException {
if (st == null&&!st.isClosed()){
st.close();
}
if (connection == null&&!connection.isClosed()){
connection.close();
}
}
}
七CRUD封装和DTO封装
1.CRUD方法封装
insert操作
public static boolean insert(student student) throws SQLException {
boolean flaa=false;
Connection con = DBhelper.getConnection();
String sql="insert into student_info values (?,?,?,?,?,?)";
PreparedStatement st=con.prepareStatement(sql);
st.setInt(1,student.getId());
st.setString(2,student.getSex());
st.setString(3,student.getName());
st.setInt(4,student.getEnglish());
st.setInt(5,student.getEnglish());
st.setInt(6,student.getChinese());
int n= st.executeUpdate();
//关闭连接
DBhelper.close(st,con);
return n>0;
}
delete操作
public static boolean delete(int id) throws SQLException {
Connection con = DBhelper.getConnection();
//编写sql语句
String sql="delete from student_info where id=?";
PreparedStatement st=con.prepareStatement(sql);
//填充
st.setInt(1,id);
int n=st.executeUpdate();
//关闭流
DBhelper.close(st,con);
return n>0;
}
update操作
public static boolean update(student student) throws SQLException {
//建立连接
Connection con = DBhelper.getConnection();
//编写sql语句
String sql="UPDATE student_info set sex=?,name=?,english=?,math=?, chinese=? where id=?";
//填充数据
PreparedStatement st=con.prepareStatement(sql);
st.setString(1, student.getSex());
st.setString(2, student.getName());
st.setInt(3,student.getEnglish());
st.setInt(4, student.getMath());
st.setInt(5, student.getChinese());
st.setInt(6, student.getId());
int n= st.executeUpdate();
//关闭流
DBhelper.close(st,con);
return n>0;
}
2.DTO封装
主要用于远程调用等需要大量传输对象的地方。例如query操作查询
query(单条数据)操作
public List<student> getstudent() throws SQLException {
List<student>list=new ArrayList<student>();
Connection con= DBhelper.getConnection();
Statement statement=con.createStatement();
//定义sql语句
String sql="SELECT * from student_info";
//执行sql语句
ResultSet res=statement.executeQuery(sql);
while(res.next()){
int id=res.getInt("id");
String sex=res.getString("sex");
String name=res.getString("name");
int english=res.getInt("english");
int math=res.getInt("math");
int chinese=res.getInt("chinese");
//创建对象,将其加入到对象的集合当中
student student=new student(id,sex,name,english,math,chinese);
list.add(student);
}
//关闭流
DBhelper.close(res,statement,con);
return list;
}
query(所有数据)操作
public student getStudent(int id) throws SQLException {
Connection connection = DBhelper.getConnection();
String sql="SELECT * from student_info where id="+id+"";
Statement statement = connection.createStatement();
ResultSet re=statement.executeQuery(sql);
student student=null;
if (re.next()) {
//拿出相应的字段
id=re.getInt("id");
String sex=re.getString("sex");
String name=re.getString("name");
int english=re.getInt("english");
int math=re.getInt("math");
int chinese=re.getInt("chinese");
//创建对象
student=new student(id,sex,name,english,math,chinese);
}
//关闭流
DBhelper.close(re,statement,connection);
return student;
}
八.DAO封装
就是将所有的CRUD放入到一个类中,此时,我们可以通过一个类来调用其中的方法,从而大大降低代码重复性
public class test {
//1.获取信息操作
public List<student> getstudent() throws SQLException {
List<student>list=new ArrayList<student>();
Connection con= DBhelper.getConnection();
Statement statement=con.createStatement();
//定义sql语句
String sql="SELECT * from student_info";
//执行sql语句
ResultSet res=statement.executeQuery(sql);
while(res.next()){
int id=res.getInt("id");
String sex=res.getString("sex");
String name=res.getString("name");
int english=res.getInt("english");
int math=res.getInt("math");
int chinese=res.getInt("chinese");
//创建对象,将其加入到对象的集合当中
student student=new student(id,sex,name,english,math,chinese);
list.add(student);
}
//关闭流
DBhelper.close(res,statement,con);
return list;
}
//2.获取单条信息操作
public student getStudent(int id) throws SQLException {
Connection connection = DBhelper.getConnection();
String sql="SELECT * from student_info where id="+id+"";
Statement statement = connection.createStatement();
ResultSet re=statement.executeQuery(sql);
student student=null;
if (re.next()) {
//拿出相应的字段
id=re.getInt("id");
String sex=re.getString("sex");
String name=re.getString("name");
int english=re.getInt("english");
int math=re.getInt("math");
int chinese=re.getInt("chinese");
//创建对象
student=new student(id,sex,name,english,math,chinese);
}
//关闭流
DBhelper.close(re,statement,connection);
return student;
}
//插入操作
public static boolean insert(student student) throws SQLException {
boolean flaa=false;
Connection con = DBhelper.getConnection();
String sql="insert into student_info values (?,?,?,?,?,?)";
PreparedStatement st=con.prepareStatement(sql);
st.setInt(1,student.getId());
st.setString(2,student.getSex());
st.setString(3,student.getName());
st.setInt(4,student.getEnglish());
st.setInt(5,student.getEnglish());
st.setInt(6,student.getChinese());
int n= st.executeUpdate();
//关闭连接
DBhelper.close(st,con);
return n>0;
}
//删除操作
public static boolean delete(int id) throws SQLException {
Connection con = DBhelper.getConnection();
//编写sql语句
String sql="delete from student_info where id=?";
PreparedStatement st=con.prepareStatement(sql);
//填充
st.setInt(1,id);
int n=st.executeUpdate();
//关闭流
DBhelper.close(st,con);
return n>0;
}
//修改操作
public static boolean update(student student) throws SQLException {
//建立连接
Connection con = DBhelper.getConnection();
//编写sql语句
String sql="UPDATE student_info set sex=?,name=?,english=?,math=?, chinese=? where id=?";
//填充数据
PreparedStatement st=con.prepareStatement(sql);
st.setString(1, student.getSex());
st.setString(2, student.getName());
st.setInt(3,student.getEnglish());
st.setInt(4, student.getMath());
st.setInt(5, student.getChinese());
st.setInt(6, student.getId());
int n= st.executeUpdate();
//关闭流
DBhelper.close(st,con);
return n>0;
}
}
九.综合案例(学生管理系统)
1.工具类封装
package com.mysql.utils;
import java.sql.*;
public class DBhelper {
//注册驱动
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
//创建连接
public static Connection getconnection() throws SQLException {
String url = "jdbc:mysql://localhost:3306/database_user";
String root = "root";
String password = "13177936413qq";
Connection con = DriverManager.getConnection(url, root, password);
return con;
}
//关闭连接
public static void closeConnection(Connection con, Statement st, ResultSet rs) throws SQLException {
if (rs == null && !rs.isClosed()) {
rs.close();
}
if (st == null && !st.isClosed()) {
st.close();
}
if (con == null && !con.isClosed()) {
con.close();
}
}
public static void closeConnection(Statement st,Connection con) throws SQLException {
if (st==null&&!st.isClosed()) {
st.close();
}
if (con == null && !con.isClosed()) {
con.close();
}
}
}
2.学生类封装
package com.mysql.student;
public class student {
private int id;
private String sex;
private String name;
private int english;
private int math;
private int chinese;
public student() {
}
public student(int id, String sex, String name, int english, int math, int chinese) {
this.id = id;
this.sex = sex;
this.name = name;
this.english = english;
this.math = math;
this.chinese = chinese;
}
@Override
public String toString() {
return "student{" +
"id=" + id +
", sex='" + sex + '\'' +
", name='" + name + '\'' +
", english=" + english +
", math=" + math +
", chinese=" + chinese +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getEnglish() {
return english;
}
public void setEnglish(int english) {
this.english = english;
}
public int getMath() {
return math;
}
public void setMath(int math) {
this.math = math;
}
public int getChinese() {
return chinese;
}
public void setChinese(int chinese) {
this.chinese = chinese;
}
}
3.主类
package com.mysql.main;
import com.mysql.student.student;
import com.mysql.utils.DBhelper;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class demo {
static int id = 0;
static String sex = null;
static String name = null;
static int english = 0;
static int math = 0;
static int chinese = 0;
static Connection con = null;
static String sql = null;
static PreparedStatement st = null;
static int n = 0;
static ResultSet rs = null;
public static void main(String[] args) throws SQLException {
Scanner scanner = new Scanner(System.in);
while (true) {
logo();
int order = scanner.nextInt();
if (n == 6) {
break;
}
switch (order) {
case 1:
//添加学生信息
//建立连接
con = DBhelper.getconnection();
System.out.println("请输入要添加的学生id");
id = scanner.nextInt();
System.out.println("请输入要添加的学生性别");
sex = scanner.next();
System.out.println("请输入要添加的学生姓名");
name = scanner.next();
System.out.println("请输入要添加的学生英语成绩");
english = scanner.nextInt();
System.out.println("请输入要添加的学生数学成绩");
math = scanner.nextInt();
System.out.println("请输入要添加的学生语文成绩");
chinese = scanner.nextInt();
//定义sql语句
sql = "insert into student_info values (?,?,?,?,?,?)";
st = con.prepareStatement(sql);
//填充数据
st.setInt(1, id);
st.setString(2, sex);
st.setString(3, name);
st.setInt(4, english);
st.setInt(5, math);
st.setInt(6, chinese);
//执行sql语句
n = st.executeUpdate();
System.out.println(n > 0 ? "插入成功!" : "插入失败!");
//关闭流
DBhelper.closeConnection(st, con);
break;
case 2:
//删除学生信息
System.out.println("请输入要删去的学生id:");
id = scanner.nextInt();
con = DBhelper.getconnection();
//定义sql语句
String sql = "delete from student_info where id=?";
PreparedStatement st = con.prepareStatement(sql);
st.setInt(1, id);
n = st.executeUpdate();
System.out.println(n > 0 ? "删除成功!" : "删除失败!");
DBhelper.closeConnection(st, con);
break;
case 3:
//修改操作
System.out.println("请输入要添加的学生id");
id = scanner.nextInt();
System.out.println("请输入要添加的学生性别");
sex = scanner.next();
System.out.println("请输入要添加的学生姓名");
name = scanner.next();
System.out.println("请输入要添加的学生英语成绩");
english = scanner.nextInt();
System.out.println("请输入要添加的学生数学成绩");
math = scanner.nextInt();
System.out.println("请输入要添加的学生语文成绩");
chinese = scanner.nextInt();
con = DBhelper.getconnection();
sql = "UPDATE student_info set sex=?,name=?,english=?,math=?, chinese=? where id=?";
st = con.prepareStatement(sql);
st.setString(1, sex);
st.setString(2, name);
st.setInt(3, english);
st.setInt(4, math);
st.setInt(5, chinese);
st.setInt(6, id);
n = st.executeUpdate();
System.out.println(n > 0 ? "执行成功!" : "执行失败!");
DBhelper.closeConnection(st, con);
break;
case 4:
//显示学生所有信息
List<student> list = new ArrayList<student>();
con = DBhelper.getconnection();
sql = "SELECT * from student_info";
st = con.prepareStatement(sql);
rs = st.executeQuery();
while (rs.next()) {
id = rs.getInt("id");
sex = rs.getString("sex");
name = rs.getString("name");
english = rs.getInt("english");
math = rs.getInt("math");
chinese = rs.getInt("chinese");
student student = new student(id, sex, name, english, math, chinese);
list.add(student);
}
for (student student : list) {
System.out.println(student);
}
//关闭流
DBhelper.closeConnection(con, st, rs);
break;
case 5:
System.out.println("输入要查询学生信息id:");
id = scanner.nextInt();
con = DBhelper.getconnection();
sql = "SELECT * from student_info";
st = con.prepareStatement(sql);
rs = st.executeQuery();
if (rs.next()) {
id = rs.getInt("id");
sex = rs.getString("sex");
name = rs.getString("name");
english = rs.getInt("english");
math = rs.getInt("math");
chinese = rs.getInt("chinese");
student student = new student(id, sex, name, english, math, chinese);
System.out.println(student);
}
DBhelper.closeConnection(con, st, rs);
break;
default:
System.out.println("输入有误,重新输入");
break;
}
}
}
public static void logo() {
System.out.println("欢迎来到学生管理系统!");
System.out.println("输入指令");
System.out.println("1 添加学生信息");
System.out.println("2 删除学生信息");
System.out.println("3 修改学生信息");
System.out.println("4 显示所有学生信息");
System.out.println("5 根据学生id信息查询学生信息");
}
}