JDBC

第一章 JDBC的快速入门

1.1 概念

  • java database connection,Java数据库连接(用Java语言操作数据库)。

1.2 JDBC的本质

  • 官方(SUN公司)定义了操作所有关系型数据库的规则,即接口。各个数据库厂商去实现这套接口,提供数据库驱动的jar包。我们可以使用这套接口(JDBC)编程,真正执行代码的是驱动jar包中的实现类。

1.3 快速入门

  • 驱动的maven坐标:
<dependency>
    <groupId>mysqlgroupId>
    <artifactId>mysql-connector-javaartifactId>
    <version>5.1.48version>
dependency>
  • 示例:
package com.sunxiaping.jdbc;

import java.sql.*;

public class QuickStart {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        //获取连接
        String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false";
        String user = "root";
        String password = "123456";
        Connection connection = DriverManager.getConnection(url, user, password);
        //定义SQL语句
        String sql = " select id,name from employee ";
        //获取执行SQL的对象
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        ResultSet rs = preparedStatement.executeQuery();
        while (rs.next()) {
            int id = rs.getInt(1);
            String name = rs.getString(2);
            System.out.println(id);
            System.out.println(name);
        }
        //释放资源
        if (connection != null) {
            connection.close();
        }
        
    }
}

 

第二章 JDBC各个类详解

2.1 DriverManager

  • 驱动管理对象。

 

  • 作用:
  • ①注册驱动。
public static synchronized void registerDriver(java.sql.Driver driver){}
  • ②获取数据库连接对象。
public static Connection getConnection(String url,
        String user, String password) throws SQLException {}

2.2 Connection

  • 数据库连接对象。

 

  • 作用:
  • ①获取执行SQL的对象。
    • 获取Statement对象:
Statement createStatement() throws SQLException;
    • 获取PreparedStatement对象:
PreparedStatement prepareStatement(String sql);
  • ②管理事务。
    • 开启或关闭自动提交。  
void setAutoCommit(boolean autoCommit) throws SQLException;
    • 提交事务。  
void commit() throws SQLException;
    • 回滚事务。  
void rollback() throws SQLException;

2.3 Statement

  • 执行静态SQL的对象。

 

  • 执行DML或DDL语句:
int executeUpdate(String sql) throws SQLException;
  • 执行DQL语句:
ResultSet executeQuery(String sql) throws SQLException;

2.4 ResultSet

  • 结果集对象,封装查询结果。

 

  • 游标向下移动一行:
boolean next() throws SQLException;
  • 获取数据:
Xxx getXxx(int columnIndex) throws SQLException; // cloumnIndex代表列的编号,从1开始
Xxx getXxx(String columnLabel) throws SQLException; //cloumnLable代表列的名称 

2.5 PreparedStatement

  • 执行预编译SQL的对象。
  • 可以用来解决SQL注入问题。

 

  • 示例:
package com.sunxiaping.jdbc;

import java.sql.*;

public class QuickStart {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        //获取连接
        String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false";
        String user = "root";
        String password = "123456";
        Connection connection = DriverManager.getConnection(url, user, password);
        //定义SQL语句
        String sql = " select id ,`name` from employee where id = ? ";

        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        preparedStatement.setInt(1, 1);

        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) {
            int id = resultSet.getInt(1);
            String name = resultSet.getString(2);
            System.out.println("id:" + id + ",name=" + name);
        }

        if (connection != null) {
            connection.close();
        }


    }
}

 

第三章 JDBC之CRUD

3.1 增加

  • 示例:
package com.sunxiaping.jdbc;

import java.sql.*;

public class QuickStart {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        //获取连接
        String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false";
        String user = "root";
        String password = "123456";
        Connection connection = DriverManager.getConnection(url, user, password);
        //定义SQL语句
        String sql = " insert into employee (name) values ('zhangsan') ";

        Statement statement = connection.createStatement();

        int count = statement.executeUpdate(sql);

        System.out.println(count);

        if (connection != null) {
            connection.close();
        }
    }
}

3.2 更新

  • 示例:
package com.sunxiaping.jdbc;

import java.sql.*;

public class QuickStart {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        //获取连接
        String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false";
        String user = "root";
        String password = "123456";
        Connection connection = DriverManager.getConnection(url, user, password);
        //定义SQL语句
        String sql = " update employee set name = 'xuweiwei' where id = 1 ";

        Statement statement = connection.createStatement();

        int count = statement.executeUpdate(sql);

        System.out.println(count);

        if (connection != null) {
            connection.close();
        }
    }
}

3.3 删除

  • 示例:
package com.sunxiaping.jdbc;

import java.sql.*;

public class QuickStart {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        //获取连接
        String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false";
        String user = "root";
        String password = "123456";
        Connection connection = DriverManager.getConnection(url, user, password);
        //定义SQL语句
        String sql = " delete from employee where id = 5 ";

        Statement statement = connection.createStatement();

        int count = statement.executeUpdate(sql);

        System.out.println(count);

        if (connection != null) {
            connection.close();
        }
    }
}

3.4 DDL

  • 示例:
package com.sunxiaping.jdbc;

import java.sql.*;

public class QuickStart {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        //获取连接
        String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false";
        String user = "root";
        String password = "123456";
        Connection connection = DriverManager.getConnection(url, user, password);
        //定义SQL语句
        String sql = " create table student(id int primary key ,name varchar (255)) ";

        Statement statement = connection.createStatement();

        int count = statement.executeUpdate(sql);

        System.out.println(count);

        if (connection != null) {
            connection.close();
        }
    }
}

 

第四章 事务管理

4.1 概述

  • 一个包含多个步骤的业务操作。如果这个业务操作被事务管理,那么这多个步骤要么同时成功,要么同时失败。

4.2 步骤

  • 开启事务。
  • 提交事务。
  • 回滚事务。

4.3 应用示例

  • 示例:
CREATE TABLE `account`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `money` double NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
)
INSERT INTO `account` VALUES (1, '张三', 1000);
INSERT INTO `account` VALUES (2, '李四', 1000);
package com.sunxiaping.jdbc;

import java.sql.*;

public class QuickStart {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            //注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //获取连接
            String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false";
            String user = "root";
            String password = "123456";
            connection = DriverManager.getConnection(url, user, password);

            connection.setAutoCommit(false);

            String sql = " update account set money = money - 500 where id = ? ";

            preparedStatement = connection.prepareStatement(sql);

            preparedStatement.setInt(1, 1);

            int count = preparedStatement.executeUpdate();

            sql = " update account set money = money + 500 where id = ? ";
            preparedStatement = connection.prepareStatement(sql);

            preparedStatement.setInt(1, 2);

            //设置异常
            int num = 1 / 0 ;

            count = preparedStatement.executeUpdate();

            connection.commit();
        } catch (Exception e) {
            e.printStackTrace();
            if (null != connection) {
                try {
                    connection.rollback();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            }

        } finally {
            if (null != preparedStatement) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (null != connection) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}

 

第五章 数据库连接池

5.1 概述

  • 数据库连接池就是一个容器(集合),存放数据库连接的容器。
  • 当系统初始化好后,容器被创建,容器中会申请一些连接对象,当用户来访问数据库的时候,从容器中获取连接对象,当用户访问完之后,会将连接对象归还给容器。

5.2 好处

  • ①节约资源。
  • ②用户访问高效。 

5.3 实现介绍

  • ①标准接口:javax.sql.DataSource接口。
    • 获取连接:  
// 获取连接
Connection getConnection() throws SQLException;
    • 归还链接:如果连接对象Connection是从连接池中获取的,那么调用Connection的close()方法,就不会再关闭连接了,而是将连接放回到连接池中。  
  • ②一般我们不去实现它,有数据库厂商来实现。

5.4 C3p0数据库连接池

  • maven坐标:
    <dependency>
        <groupId>com.mchangegroupId>
        <artifactId>c3p0artifactId>
        <version>0.9.5.2version>
    dependency>    

 

  • 示例:
  • c3p0-config.xml
xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
    
    <default-config>
        
        <property name="checkoutTimeout">3000property>
        
        <property name="idleConnectionTestPeriod">30property>
        
        <property name="initialPoolSize">2property>
        
        <property name="maxIdleTime">30property>
        
        <property name="maxPoolSize">5property>
        
        <property name="minPoolSize">2property>
        
        <property name="maxStatements">50property>
        
        <property name="acquireIncrement">3property>
        
        <property name="driverClass">com.mysql.jdbc.Driverproperty>
        <property name="jdbcUrl">
            jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false]]>
        property>
        <property name="user">rootproperty>
        <property name="password">123456property>
    default-config>
c3p0-config>
  • DataSourceTest.java
package com.sunxiaping.jdbc;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class DataSourceTest {
    public static void main(String[] args) {
        DataSource dataSource = new ComboPooledDataSource();
        Connection connection = null;
        try {
            connection = dataSource.getConnection();

            System.out.println(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

5.5 Druid数据库连接池

  • maven坐标:
<dependency>
    <groupId>com.alibabagroupId>
    <artifactId>druidartifactId>
    <version>1.1.20version>
dependency>

 

  • 示例:
  • druid.properties
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
username=root
password=123456
# 初始化连接数
initialSize=5
#最大连接数
maxActive=10
#超时时间
maxWait=3000
  • DataSourceTest.java
package com.sunxiaping.jdbc;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DataSourceTest {
    public static void main(String[] args) {
        Connection connection = null;
        try {
            Properties properties = new Properties();
            properties.load(DataSourceTest.class.getClassLoader().getResourceAsStream("druid.properties"));

            connection = DruidDataSourceFactory.createDataSource(properties).getConnection();

            System.out.println(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

 

第六章 JDBC Template

6.1 概述

  • Spring框架对JDBC的简单封装。

6.2 开发步骤

  • ①导入jar包:
<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-jdbcartifactId>
    <version>5.1.9.RELEASEversion>
dependency>
  • ②创建JdbcTemplate对象,依赖于数据源DataSource。
JdbcTemplate jdbcTemplate = new JdbcTemplate(DruidDataSourceFactory.createDataSource(properties));
  • ③调用JdbcTemplate的方法来完成CRUD的操作。
    • 执行DML语句。增、删、改:  
public int update(String sql, @Nullable Object... args) throws DataAccessException{}
    • 将查询的结果集封装到Map集合中(查询长度只能为1条,将列名作为key,将值作为value):  
public Map queryForMap(String sql) throws DataAccessException{}
    • 将查询的结果集封装到List集合中:  
public  List queryForList(String sql, Class elementType) throws DataAccessException{}
public List> queryForList(String sql) throws DataAccessException{}
    • 将查询的结果集封装为JavaBean对象:  
public  List query(String sql, RowMapper rowMapper) throws DataAccessException{}
    • 将查询的结果集封装为对象(一般用于聚合函数的使用):  
public  T queryForObject(String sql, Class requiredType) throws DataAccessException{}

6.3 应用示例

  • 示例:修改数据
package com.sunxiaping.jdbc;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.springframework.jdbc.core.JdbcTemplate;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class JdbcTemplateTest {
    public static void main(String[] args) {
        Connection connection = null;
        try {
            Properties properties = new Properties();
            properties.load(JdbcTemplateTest.class.getClassLoader().getResourceAsStream("druid.properties"));

            JdbcTemplate jdbcTemplate = new JdbcTemplate(DruidDataSourceFactory.createDataSource(properties));

            int count = jdbcTemplate.update(" update dept set `name` = ? where id = ? ", "测试部1", 1);

            System.out.println(count);

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
View Code

 

  • 示例:查询部门为1号部门的信息
package com.sunxiaping.jdbc;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.springframework.jdbc.core.JdbcTemplate;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
import java.util.Properties;

public class JdbcTemplateTest {
    public static void main(String[] args) {
        Connection connection = null;
        try {
            Properties properties = new Properties();
            properties.load(JdbcTemplateTest.class.getClassLoader().getResourceAsStream("druid.properties"));

            JdbcTemplate jdbcTemplate = new JdbcTemplate(DruidDataSourceFactory.createDataSource(properties));

            Map map = jdbcTemplate.queryForMap("select * from dept where id = ?", 1);
            System.out.println(map);

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
View Code

 

  • 示例:将查询结果封装到List>中
package com.sunxiaping.jdbc;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.springframework.jdbc.core.JdbcTemplate;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class JdbcTemplateTest {
    public static void main(String[] args) {
        Connection connection = null;
        try {
            Properties properties = new Properties();
            properties.load(JdbcTemplateTest.class.getClassLoader().getResourceAsStream("druid.properties"));

            JdbcTemplate jdbcTemplate = new JdbcTemplate(DruidDataSourceFactory.createDataSource(properties));

            List> mapList = jdbcTemplate.queryForList(" select * from dept ");

            System.out.println(mapList);

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
View Code

 

  • 示例:将查询的结果集封装到Javabean中
package com.sunxiaping.domain;


import java.util.Objects;

public class Dept {
    private Integer id;
    private String name;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Dept dept = (Dept) o;
        return id.equals(dept.id) &&
                name.equals(dept.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name);
    }

    @Override
    public String toString() {
        return "Dept{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
View Code
package com.sunxiaping.jdbc;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.sunxiaping.domain.Dept;
import org.springframework.jdbc.core.JdbcTemplate;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;

public class JdbcTemplateTest {
    public static void main(String[] args) {
        Connection connection = null;
        try {
            Properties properties = new Properties();
            properties.load(JdbcTemplateTest.class.getClassLoader().getResourceAsStream("druid.properties"));

            JdbcTemplate jdbcTemplate = new JdbcTemplate(DruidDataSourceFactory.createDataSource(properties));

            List deptList = jdbcTemplate.query("select * from dept", (rs, rowNum) -> {
                Dept dept = new Dept();
                dept.setId(rs.getInt("id"));
                dept.setName(rs.getString("name"));
                return dept;
            });

            System.out.println(deptList);

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
View Code

 

  • 示例:查询总记录数
package com.sunxiaping.jdbc;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.springframework.jdbc.core.JdbcTemplate;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class JdbcTemplateTest {
    public static void main(String[] args) {
        Connection connection = null;
        try {
            Properties properties = new Properties();
            properties.load(JdbcTemplateTest.class.getClassLoader().getResourceAsStream("druid.properties"));

            JdbcTemplate jdbcTemplate = new JdbcTemplate(DruidDataSourceFactory.createDataSource(properties));

            Long count = jdbcTemplate.queryForObject(" select count(*) from dept ", Long.class);

            System.out.println(count);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
View Code

 

你可能感兴趣的:(JDBC)