JDBC 学习笔记+代码整理

Tip

Idea自带可视界面👉MySQL 图形化界面-CSDN博客

Idea2022无add Framework support选项👉最新版IDEA:Add web Framework Support步骤/构建JavaWeb项目步骤_idea add framework support-CSDN博客

基本步骤

1.加载驱动包Driver

2.建立与数据库的连接Connection DriverManager

3.发送SQL语句Statement

4.接收数据库返回结果executeUpdate()/executeQuery()

5.解析结果ResultSet

6.关闭连接close()

加载驱动包Driver

java 复制代码
package com.qf.JDBC;

public class JdbcDriver {
    static {
//        1.加载驱动类
        try {
//            反射获得驱动类Driver
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}

创建和数据库的连接

java 复制代码
package com.qf.JDBC;

import com.mysql.cj.jdbc.Driver;
import java.sql.*;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JdbcDriver {
    private static String url="jdbc:mysql://localhost:3306/student?serverTimezone=UTC";
//    jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf-8   5
//    jdbc:mysql://localhost:3306/student?serverTimezone=UTC  8
    private static String username="root";//自己的用户名
    private static String pass="123456";//自己的密码

    static {
//        1.加载驱动类
        try {
//            反射获得驱动类Driver
//            com.mysql.cj.jdbc.Driver 7
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

//    2.获取连接
    public static Connection getConn() {
        Connection conn=null;
        try {
            conn = DriverManager.getConnection(url, username, pass);
            System.out.println("连接成功");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return conn;
    }

    public static void main(String[] args) {
        getConn();
    }
}

发送Sql语句

例子:增加操作

java 复制代码
package com.qf.JDBC;

import com.mysql.cj.jdbc.Driver;
import java.sql.*;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Stack;

public class JdbcDriver {
    private static String url="jdbc:mysql://localhost:3306/student?serverTimezone=UTC";
//    jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf-8   5
//    jdbc:mysql://localhost:3306/student?serverTimezone=UTC  8
    private static String username="root";
    private static String pass="123456";

    static {
//        1.加载驱动类
        try {
//            反射获得驱动类Driver
//            com.mysql.cj.jdbc.Driver 7
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

//    2.获取连接
    public static Connection getConn() {
        Connection conn=null;
        try {
            conn = DriverManager.getConnection(url, username, pass);
            System.out.println("连接成功");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return conn;
    }

//    增加同学
    public static void addDept(){
        String sql="insert into student.table values('zt','男',20)";
//        获得连接
        try {
            Statement st= getConn().createStatement();
            st.executeUpdate(sql);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        addDept();
    }
}

例子:查询所有同学的信息

java 复制代码
package com.qf.JDBC;

import com.mysql.cj.jdbc.Driver;
import com.qf.JDBC.pojo.table;

import javax.swing.*;
import java.sql.*;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Stack;

public class JdbcDriver {
    private static String url="jdbc:mysql://localhost:3306/student?serverTimezone=UTC";
//    jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf-8   5
//    jdbc:mysql://localhost:3306/student?serverTimezone=UTC  8
    private static String username="root";
    private static String pass="123456";

    static {
//        1.加载驱动类
        try {
//            反射获得驱动类Driver
//            com.mysql.cj.jdbc.Driver 7
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

//    2.获取连接
    public static Connection getConn() {
        Connection conn=null;
        try {
            conn = DriverManager.getConnection(url, username, pass);
            System.out.println("连接成功");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return conn;
    }

    //查询所有学生信息
    public static ArrayList<table> queryAll(){
        ArrayList<table> list=new ArrayList<>();
        String sql="select * from student.table";
//        获得连接
        Connection conn=getConn();
        Statement st=null;
        try {
            st=conn.createStatement();
            ResultSet r=st.executeQuery(sql);
            while (r.next()){
                table t=new table(r.getString(1),r.getString(2),r.getInt("age"));//分别是第一列 第二列 age列
                list.add(t);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                st.close();//先打开的流后关闭
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return list;
    }

    public static void main(String[] args) {
        ArrayList<table> arrayList=queryAll();
        for (table a:arrayList) {
            System.out.println(a);
        }
    }

}
java 复制代码
package com.qf.JDBC.pojo;

import java.io.Serializable;

public class table implements Serializable {//实体类 属性与表一致
    private String name;
    private String gender;
    private int age;

    public table(String name, String gender, int age) {
        this.name = name;
        this.gender = gender;
        this.age = age;
    }

    public table() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "table{" +
                "name='" + name + '\'' +
                ", gender='" + gender + '\'' +
                ", age=" + age +
                '}';
    }
}

例子:修改和删除

++继续用上面的table实体类++

java 复制代码
package com.qf.JDBC;

import com.mysql.cj.jdbc.Driver;
import com.qf.JDBC.pojo.table;

import javax.swing.*;
import java.sql.*;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Stack;

public class JdbcDriver {
    private static String url="jdbc:mysql://localhost:3306/student?serverTimezone=UTC";
//    jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf-8   5
//    jdbc:mysql://localhost:3306/student?serverTimezone=UTC  8
    private static String username="root";
    private static String pass="123456";

    static {
//        1.加载驱动类
        try {
//            反射获得驱动类Driver
//            com.mysql.cj.jdbc.Driver 7
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

//    2.获取连接
    public static Connection getConn() {
        Connection conn=null;
        try {
            conn = DriverManager.getConnection(url, username, pass);
            System.out.println("连接成功");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return conn;
    }


//    修改部门
        public static void updateDept(){
        String sql="update student.table set age=21 where name='zt'";
//        获得连接
        try {
            Statement st= getConn().createStatement();
            st.executeUpdate(sql);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

//删除
    public static void deleteDept(){
        String sql="delete from student.table where name='xx'";
//        获得连接
        try {
            Statement st= getConn().createStatement();
            st.executeUpdate(sql);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        updateDept();
        deleteDept();
    }
}

JDBC实现分层处理

package com.xxxx.JDBC;//根包

common 公共包(所有模块共用的类,数据库连接类,分页处理)

pojo(entiy)实体类的包(和表一一对应的类叫做实体类,Dept Emp)

test 测试包

dao 数据访问对象(数据访问层,对数据表增删改查的代码)

service 业务层(业务逻辑)

目录

DBConn

java 复制代码
package com.qf.JDBC.common;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConn {
    private static String url="jdbc:mysql://localhost:3306/student?serverTimezone=UTC";
    //    jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf-8   5
//    jdbc:mysql://localhost:3306/student?serverTimezone=UTC  8
    private static String username="root";
    private static String pass="123456";

    static {
//        1.加载驱动类
        try {
//            反射获得驱动类Driver
//            com.mysql.cj.jdbc.Driver 7
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    //    2.获取连接
    public static Connection getConn() {
        Connection conn=null;
        try {
            conn = DriverManager.getConnection(url, username, pass);
            System.out.println("连接成功");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return conn;
    }
}

StuDao

java 复制代码
package com.qf.JDBC.dao;

import com.qf.JDBC.pojo.Student;

public interface StuDao {
    void addStu(Student s);
    void updateStu(Student s);
    void delStu(Student s);

}

StuDaoImpl

java 复制代码
package com.qf.JDBC.dao;

import com.qf.JDBC.common.DBConn;
import com.qf.JDBC.pojo.Student;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public class StuDaoImpl extends DBConn implements StuDao{

    @Override
    public void addStu(Student s) {
        String sql="insert into student.table(name,gender,age) values (?,?,?)";
//        获得连接
        Connection conn =DBConn.getConn();
        PreparedStatement st=null;
        try {
            st= getConn().prepareStatement(sql);
            st.setString(1,s.getName());
            st.setString(2,s.getGender());
            st.setInt(3,s.getAge());
            //执行语句
            int r= st.executeUpdate();
            if(r>=1){
                System.out.println("新增成功");
            }else {
                System.out.println("新增失败");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                st.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public void updateStu(Student s) {

    }

    @Override
    public void delStu(Student s) {

    }
}

Student

java 复制代码
package com.qf.JDBC.pojo;

public class Student {
    private String name;
    private String gender;
    private int age;

    public Student(String name, String gender, int age) {
        this.name = name;
        this.gender = gender;
        this.age = age;
    }

    public Student() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

StuService

java 复制代码
package com.qf.JDBC.service;

import com.qf.JDBC.dao.StuDao;
import com.qf.JDBC.dao.StuDaoImpl;
import com.qf.JDBC.pojo.Student;

public class StuService {
    public static void main(String[] args) {
        StuDao stuDao=new StuDaoImpl();
        stuDao.addStu(new Student("张三","男",25));
    }
}
相关推荐
yuwinter22 分钟前
鸿蒙HarmonyOS学习笔记(2)
笔记·学习·harmonyos
JH307329 分钟前
Oracle与MySQL中CONCAT()函数的使用差异
数据库·mysql·oracle
蓝染-惣右介31 分钟前
【MyBatisPlus·最新教程】包含多个改造案例,常用注解、条件构造器、代码生成、静态工具、类型处理器、分页插件、自动填充字段
java·数据库·tomcat·mybatis
冷心笑看丽美人32 分钟前
Spring框架特性及包下载(Java EE 学习笔记04)
数据库
游走于计算机中摆烂的1 小时前
启动前后端分离项目笔记
java·vue.js·笔记
武子康2 小时前
Java-07 深入浅出 MyBatis - 一对多模型 SqlMapConfig 与 Mapper 详细讲解测试
java·开发语言·数据库·sql·mybatis·springboot
代码吐槽菌2 小时前
基于SSM的毕业论文管理系统【附源码】
java·开发语言·数据库·后端·ssm
你可以叫我仔哥呀2 小时前
ElasticSearch学习笔记三:基础操作(一)
笔记·学习·elasticsearch
maxiumII2 小时前
Diving into the STM32 HAL-----DAC笔记
笔记·stm32·嵌入式硬件
路有瑶台2 小时前
MySQL数据库学习(持续更新ing)
数据库·学习·mysql