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));
    }
}
相关推荐
索然无味io13 分钟前
跨站请求伪造之基本介绍
前端·笔记·学习·web安全·网络安全·php
kikikidult18 分钟前
Ubuntu20.04安装openMVS<成功>.colmap<成功>和openMVG<失败(已成功)>
笔记·学习
爱学习的白杨树24 分钟前
什么是MVCC?
java·服务器·数据库
胡西风_foxww27 分钟前
【es6复习笔记】集合Set(13)
前端·笔记·es6·set·集合
平行线也会相交39 分钟前
云图库平台(三)——后端用户模块开发
数据库·spring boot·mysql·云图库平台
灵槐梦41 分钟前
【速成51单片机】2.点亮LED
c语言·开发语言·经验分享·笔记·单片机·51单片机
MUTA️2 小时前
RT-DETR学习笔记(2)
人工智能·笔记·深度学习·学习·机器学习·计算机视觉
恒辉信达2 小时前
hhdb客户端介绍(53)
数据库·mysql·hhdb·数据库可视化界面客户端
codists2 小时前
《计算机组成及汇编语言原理》阅读笔记:p82-p85
笔记
ladymorgana2 小时前
【运维笔记】windows 11 中提示:无法成功完成操作,因为文件包含病毒或潜在的垃圾软件。
运维·windows·笔记