liqiju

本文参考:Java Web程序设计教程、菜鸟教程

阿里云盘分享(下载贼快)

mysql-connector-java-5.1.47.jar 下载

jdk-8-windows-x64 下载

jdk-11.0.7_windows-x64 下载

1. 步骤
  1. 加载驱动程序

    注:mysql驱动jar包版本最好和mysql版本一致

    final String JDBC_DRIVER_5 = "com.mysql.jdbc.Driver";
    final String JDBC_Driver_8 = "com.mysql.cj.jdbc.Driver";
    // 驱动jar包 5.*
    Class.forName(JDBC_DRIVER_5);
    // 驱动jar包 >= 8.0
    ClassforName(JDBC_Driver_8);
    
  2. 获取数据库连接

    注:mysql版本不同url的写法也略有差别

    final String URL = "jdbc:mysql://localhost:3306/数据库名?useSSL=false";
    final String USER = "root";
    final String PASSWORD = "123456";
    Connection con = DriverManager.getConnection(URL, USER, PASSWORD);
    
  3. 执行各种SQL语句

    Statement stat = con.createStatement();
    

    三种Statement对象:

    • Statement:用于执行不带参数的简单SQL语句;
    • PreparedStatement:Statement的子接口类型,PreparedStatement对象用于执行带或不带in参数的预编译SQL语句;
    • CallableStatement:PreparedStatement的子接口类型,CallableStatement对象用于执行对数据库已存在的存储过程的调用;
  4. 获取查询结果

    String sql = "select * from website";
    ResultSet resultSet = stat.executeQuery(sql);
    
  5. 关闭资源

    注:依次关闭资源

    resultSet.close();
    stat.close();
    con.close();
    
2. 小试牛刀

先在mysql中创建用到的数据库,数据表,并填充数据:

# 创建test数据库
create database test;	
# 选择test数据库
use test; 
# 建表
create table website
(
    id      int auto_increment primary key,
    name    char(20)     default \'\' not null comment \'站点名称\',
    url     varchar(255) default \'\' not null,
    alexa   int          default 0  not null comment \'Alexa 排名\',
    country char(10)     default \'\' not null comment \'国家\'
);
# 添加数据
INSERT INTO `website`
VALUES (\'1\', \'Google\', \'https://www.google.cm/\', \'1\', \'USA\'),
       (\'2\', \'淘宝\', \'https://www.taobao.com/\', \'13\', \'CN\'),
       (\'3\', \'菜鸟教程\', \'http://www.runoob.com\', \'5892\', \'\'),
       (\'4\', \'微博\', \'http://weibo.com/\', \'20\', \'CN\'),
       (\'5\', \'Facebook\', \'https://www.facebook.com/\', \'3\', \'USA\');

请确保:

  1. 已成功安装jdk
  2. 已成功安装mysql,并打开了mysql服务
  3. 已成功导入mysql驱动jar包
  4. 已经创建好数据库和数据表并导入了数据
import java.sql.*;

public class JDBCTest {
    public static void main(String[] args) {
        final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
        final String URL = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC";
        final String USERNAME = "root";
        final String PASSWORD = "123456";	// 数据库密码(换成你自己的)
        String sql = "select * from website";
        try {
            // 1. 加载mysql驱动
            Class.forName(JDBC_DRIVER);
            // 2. 获取连接
            Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
            // 3. 执行sql
            Statement statement = connection.createStatement();
            // 4. 获取结果
            ResultSet resultSet = statement.executeQuery(sql);
            while (resultSet.next()) {
                System.out.print(resultSet.getInt("id") + ",");
                System.out.print(resultSet.getString("name") + ",");
                System.out.println(resultSet.getString("url"));
            }
            // 5. 依次关闭资源
            resultSet.close();
            statement.close();
            connection.close();
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }
}
3. 什么是JDBC?

​ JDBC是一套面向对象的应用编程接口,它制定了统一的访问各类关系数据库的标准接口,为各个数据库厂商提供了标准接口的实现。通过使用JDBC技术,开发人员可以用纯java和标准的SQL语句编写完整的数据库应用程序。

4. JDBC架构

image

5. JDBC API中的接口和类
  • DriverManager: 这个类是JDBC的管理层,作用域用户和驱动程序之间。它跟踪可用的驱动程序,并在数据库和响应的驱动程序之间建立连接。
  • Driver:此接口处理与数据库服务器的通信,通常由数据库厂商实现该接口。在进行Java Web开发时,程序员只需根据程序使用的驱动程序类型进行装载就行。
  • Connection:此接口代表数据库连接。与数据库的所有通信都通过该对象连接。
  • Statement:此接口代表SQL语句对象。可以向数据库发送任何SQL语句。
  • ResultSet:它封装了查询返回的结果集对象。结果集是一个存储查询结果的对象,但是结果集不仅仅具有存储功能,同时后具有操纵数据的功能,可能完成对数据的更新等。
  • SQLException:这个类处理发生在数据库操作过程中的任何错误。
* 进阶实战
step1: 创建WebsiteBean

WebsiteBean就是一个javaBean,javaBean实际上就是一个Java类,用于封装从数据库中查询出的数据.

public class WebsiteBean {
    private int id;
    private String name;
    private String url;
    private int alexa;  // 排名
    private String country; // 国家

    public WebsiteBean() {
    }

    public WebsiteBean(int id, String name, String url, int alexa, String country) {
        this.id = id;
        this.name = name;
        this.url = url;
        this.alexa = alexa;
        this.country = country;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public int getAlexa() {
        return alexa;
    }

    public void setAlexa(int alexa) {
        this.alexa = alexa;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    @Override
    public String toString() {
        return "WebsiteBean{" +
                "id=" + id +
                ", name=\'" + name + \'\\'\' +
                ", url=\'" + url + \'\\'\' +
                ", alexa=" + alexa +
                ", country=\'" + country + \'\\'\' +
                \'}\';
    }
}
step2: 创建JDBC工具类

用于提供数据库连接。避免每次连接数据库都要写一遍,提高代码重用性

public class DbUtil {
    private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    // test是数据库名称(改成你自己的数据库)
    private static final String DB_URL = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC";
    // 数据库用户名
    private static final String USERNAME = "root";
    // 数据库密码(改成你自己的密码)
    private static final String PASSWORD = "123456";
    private static Connection connection = null;

    static {
        try {
            // 1. 加载mysql的驱动到java虚拟机
            Class.forName(JDBC_DRIVER);
            // 2. 获取数据库连接
            connection = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);
            // connection.setAutoCommit(true); // 默认自动提交
        } catch (ClassNotFoundException classNotFoundException) {
            classNotFoundException.printStackTrace();
        } catch (SQLException sqlException) {
            sqlException.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        return connection;
    }
}
step3: 创建操作类WebsiteDao

WebsiteDao中封装了操作相关数据表的方法。如:添加数据、删除、修改、查询数据等

public class WebsiteDao {
    // 获取连接
    private static final Connection connection = DbUtil.getConnection();

    // 添加
    public int addWebsite(WebsiteBean website) throws SQLException {
        // 3. 执行SQL语句
        String sql = "insert into website(name, url, alexa, country) value(?,?,?,?)";
        // 预编译SQL,提高sql执行效率,避免SQL注入
        PreparedStatement ptmt = connection.prepareStatement(sql);
        // 传参. 1对应第一个? name;2对应第二个? url ...
        ptmt.setString(1, website.getName());
        ptmt.setString(2, website.getUrl());
        ptmt.setInt(3, website.getAlexa());
        ptmt.setString(4, website.getCountry());
        // 4. 返回结果,这里返回受影响的行数
        int rows = ptmt.executeUpdate();
        // 5. 关闭资源
        ptmt.close();
        connection.close();
        return rows;
    }

    // 更新
    public int updateWebsite(WebsiteBean website) throws SQLException {
        String sql = "update website set name=?, url=?, alexa=?, country=? where id=?";
        // 预编译SQL,提高sql执行效率,避免SQL注入
        PreparedStatement ptmt = connection.prepareStatement(sql);
        ptmt.setString(1, website.getName());
        ptmt.setString(2, website.getUrl());
        ptmt.setInt(3, website.getAlexa());
        ptmt.setString(4, website.getCountry());
        ptmt.setInt(5, website.getId());
        // 执行并返回受影响的行数
        int rows = ptmt.executeUpdate();
        // 关闭资源
        ptmt.close();
        connection.close();
        return rows;
    }

    // 删除
    public int delWebsite(int id) throws SQLException {
        String sql = "delete from website where id = ?";
        // 预编译SQL,提高sql执行效率,避免SQL注入
        PreparedStatement ptmt = connection.prepareStatement(sql);
        ptmt.setInt(1, id);
        // 执行并返回受影响的行数
        int rows = ptmt.executeUpdate();
        // 关闭资源
        ptmt.close();
        connection.close();
        return rows;
    }

    // 查询所有
    public List getAll() throws SQLException {
        String sql = "select * from website";
        // 预编译SQL,提高sql执行效率,避免SQL注入
        PreparedStatement ptmt = connection.prepareStatement(sql);
        // 执行并返回
        ResultSet rSet = ptmt.executeQuery();

        // 将结果封装在list里面
        List<WebsiteBean> websiteList = new ArrayList<>();
        while (rSet.next()) {
            WebsiteBean website = new WebsiteBean();
            website.setId(rSet.getInt("id"));
            website.setName(rSet.getString("name"));
            website.setCountry(rSet.getString("country"));
            website.setUrl(rSet.getString("url"));
            website.setAlexa(rSet.getInt("alexa"));
            websiteList.add(website);
        }
        // 关闭资源
        rSet.close();
        ptmt.close();
        connection.close();
        return websiteList;
    }

    // 根据主键id查询
    public WebsiteBean get(int id) throws SQLException {
        WebsiteBean website = null;
        String sql = "select * from website where id = ?";
		// 预编译SQL,提高sql执行效率,避免SQL注入
        PreparedStatement ptmt = connection.prepareStatement(sql);
        ptmt.setInt(1, id);
        ResultSet rSet = ptmt.executeQuery();
        // 封装
        while (rSet.next()) {
            website = new WebsiteBean();
            website.setId(rSet.getInt("id"));
            website.setName(rSet.getString("name"));
            website.setCountry(rSet.getString("country"));
            website.setUrl(rSet.getString("url"));
            website.setAlexa(rSet.getInt("alexa"));
        }
        // 关闭资源
        rSet.close();
        ptmt.close();
        connection.close();
        return website;
    }
}
step4: 测试
public class Test {
    public static void main(String[] args) {
        WebsiteDao dao = new WebsiteDao();
        try {
            System.out.println("-------------返回所有数据------------");
			// forEach()中为java8新特性lamabda表达式
            dao.getAll().forEach(item -> System.out.println(item));

            System.out.println("-------------根据id返回数据--------------");
            System.out.println(dao.get(3));

            System.out.println("-------------add 返回影响行数--------------");
            // 这里的id = 99实际无效,数据库中id是自增的
            int addRows = dao.addWebsite(new WebsiteBean(99, "天猫", "https://tanmao.com", 999, "China"));
            System.out.println(addRows);
            
            System.out.println("-------------添加后------------");
            dao.getAll().forEach(item -> System.out.println(item));

            System.out.println("-------------update 返回影响行数--------------");
            int updateRows = dao.updateWebsite(new WebsiteBean(4, "微博", "https://weibo.cn", 10, "China"));
            System.out.println(updateRows);
            
            System.out.println("-------------更新后------------");
            dao.getAll().forEach(item -> System.out.println(item));

            System.out.println("-------------delete 返回影响行数--------------");
            int delRows = dao.delWebsite(99);
            System.out.println(delRows);
            
            System.out.println("-------------删除后------------");
            dao.getAll().forEach(item -> System.out.println(item));
            
        } catch (SQLException sqlException) {
            sqlException.printStackTrace();
        }
    }
}

欢迎每位高手留言指正

分类:

技术点:

相关文章: