从来就没有救世主  也不靠神仙皇帝  要创造人类的幸福  全靠我们自己  

JDBC

 

1. 下载依赖文件 mysql-connector-java-version.jar,添加到项目

 

2. JDBC连接数据库的过程

(1)注册数据库驱动

  即加载数据库驱动相关的类到JVM

 

(2)构建数据库连接的URL

 

(3)获取数据库连接对象Connection

 

(4)SQL操作

 

3. 相关的接口和类

  3.1 DriverManager类

  管理驱动程序,建立应用和数据库之间的连接

(1)注册驱动

static void deregisterDriver(Driver driver) 从DriverManager管理列表中删除一个驱动
static void registerDriver(Driver driver) 向DriverManager注册一个驱动对象
static Enumeration<Driver> getDrivers() 获取当前DriverManager中已加载的全部驱动

(2)建立数据库连接

static Connection getConnection(String url)
static Connection getConnection(String url,Properties info)
static Connection getConnection(String url,String user,String password)

  url:"jdbc:mysql://ip:port/数据库名"

 

  3.2 Connection接口

  数据库连接

Statement createStatement()  执行SQL的对象
PreparedStatement prepareStatement(String sql) 将参数化的SQL语句预编译存储在PreparedStatement对象中

void close() 释放Connection对象的数据库连接占用的JDBC资源
boolean isClosed()  是否与数据库断开连接

boolean isReadOnly() Connection对象是否只读
void setReadOnly(boolean readOnly)  将Connection对象的连接模式设置只读
//事务
//开启事务
void setAutoCommit(boolean autoCommit) true,自动提交   false,手动提交(开启事务)
boolean getAutoCommit()  判断是自动提交还是手动提交
//保存点
Savepoint setSavepoint()   在当前事务中创建一个未命名的保存点
Savepoint setSavepoint(String name) 在当前事务中创建一个命名的保存点
void releaseSavepoint(Savepoint savepoint)  在当前事务中移除指定的保存点和后续保存点
//回滚事务
void rollback()  (手动提交模式下),回滚事务,释放Connection持有的数据库锁
void rollBakc(Savepoint savepoint) 回滚事务到该保存点

//提交事务
void commit()  (手动提交模式时)提交事务,释放Connection对象当前持有的所有数据库锁

//
void setTransactionIsolation(int level) 设置Connection对象的事物隔离级别
int getTransactionIsolation()  获取

 

  3.3 Statement

  执行SQL语句

void addBatch(String sql)  添加sql语句到Statement的当前命令列表中
void cleatBatch()    清空命令列表
int[] executeBatch()  将一批命令提交给数据库执行,返回更行计数数组

boolean execute(String sql)  
ResultSet executeQuery(String sql)    执行DQL(select)语句
int executeUpdate(String sql)  执行DML(insert、update、delete)、DDL(create、alter、drop)语句

void close()
boolean isClosed() 

Connection getConnection()

 

  3.4 ResultSet

  结果集

//
boolean next()  游标向下移动一行
boolean previous() 游标向上移动一行
boolean last()  游标移动到最后一行
boolean first() 游标移动到第一行
boolean absolute(int row) 游标移动到给定行
void beforeFirst()  移动游标到第一行之前
void afterLast() 移动游标到最后一行之后

//
InputStream getBinaryStream(String col) 以字节流方式获取当前行的指定列的值
Xx getXx(int colIndex) 以Xx方式获取当前行指定列的值(idnex从1开始) 
Xx getXx(String colLabel) 以Xx方式获取当前行指定列的值(参数为列名称)

//
ResultSetMetaData getMetaData()

  3.5  ResultSetMetaData

int getColumnCount() 列数
String getColumnName(int column)  获取列的字段原名
String getColumnLabel(int column) 获取用来展示的名字(SELECT name1 as label1,name2 as label2 FROM xx)

 

 

  3.6 PreparedStatement

  继承自Statement

 

void setBianryStream(int paramIndex,InputStream x)  输入流x作为第paramIndex个参数
void setXx(int paramIndex,Xx x)  x作为第paramIndex个参数

 

  例子:

Connection conn = DriverManager.getConnection(url,userName,password);
String sql = "insert into table1(name,price,bookCount,author) values(?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,"name1");
ps.setDouble(2,3.14);
ps.setInt(3,2);
ps.setString(4,"author1");
int row = ps.executeUpdate();

 

 

 

 

 

 

 

 

4. 例子

   jdbc.properties

url=jdbc:mysql://localhost:3306/testx
user=root
password=xxx
driver=com.mysql.jdbc.Driver

  JDBC工具类:

package utils.jdbcUtils;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;

public class JdbcUtils {
    private static String url;
    private static String user;
    private static String password;
    private static String driver;

    static {
        try {
            Properties pro = new Properties();

            //
            ClassLoader classLoader = JdbcUtils.class.getClassLoader();
            URL proUrl = classLoader.getResource("jdbc.properties");
            String proPath = proUrl.getPath();


            pro.load(new FileReader(proPath));
            url = pro.getProperty("url");
            user = pro.getProperty("user");
            password = pro.getProperty("password");
            driver = pro.getProperty("driver");
        }catch(FileNotFoundException e) {
            e.printStackTrace();
        }catch(IOException e) {
            e.printStackTrace();
        }
    }

    /*
    * 获取连接
    */
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url,user,password);
    }

    /*
    * 断开连接,释放资源
    */
    public static void close(Connection conn,Statement stmt,PreparedStatement pst,ResultSet res) {
        if(res != null) {
            try {
                res.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            res = null;
        }

        if(pst != null) {
            try {
                pst.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            pst = null;
        }

        if(stmt != null) {
            try {
                stmt.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            stmt = null;
        }

        if(conn != null) {
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            conn = null;
        }
    }
}

 

  调用:

package com.jdbc;

import utils.jdbcUtils.JdbcUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class TestJBDC2 {
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet result = null;
        try {
            conn = JdbcUtils.getConnection();
            stmt = conn.createStatement();
            String sql = "select * from person";
            result = stmt.executeQuery(sql);
            //获取结果集中数据
            ArrayList<Map<String,String>> res = new ArrayList<Map<String,String>>();
            ArrayList<String> colNames = new ArrayList<String>();
            ResultSetMetaData rsmd = result.getMetaData();
            //保存列名
            for(int i=1;i<=rsmd.getColumnCount();i++) {
                String name = rsmd.getColumnName(i);
                colNames.add(name);
            }
            //每行数据保存到Map,所有行数据保存到List
            while(result.next()) {
                Map<String,String> row = new HashMap<String,String>();
                for(int i=0;i<colNames.size();i++) {
                    String value = result.getString(colNames.get(i));
                    row.put(colNames.get(i),value);
                }
                res.add(row);
            }
            //打印数据
            for(int i=0;i<colNames.size();i++) {
                System.out.print(colNames.get(i)+"  ");
            }
            System.out.println();
            for(int i=0;i<res.size();i++) {
                Map<String,String> map = res.get(i);
                for(String key:map.keySet()) {
                    System.out.print(map.get(key)+"  ");
                }
                System.out.println();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}

 

 

5. 问题

(1)较新的mysql驱动包为

com.mysql.cj.jdbc.Driver

 

(2)时区报错

  在URL后加

jdbc:mysql://localhost:3306/stus?serverTimezone=UTC

 

 (3)插入数据乱码

  检查前端页面编码、检查request设置编码

  在jdbc的url后加: useUnicode=true&characterEncoding=utf8

-------------------------------------------------------------------------------------------------------------------------------------------------------

数据库连接池

1. 概念

  数据库连接池就是连接对象组成的容器集合,容器创建后会申请一些连接对象,需要访问数据库时,从容器中获取连接对象,访问完之后,将连接对象归还给容器。使得访问更高效,资源得到节约。

 

2. 实现

(1)标准接口

  javax.sql.DataSource  数据库厂商去实现

  方法:

//获取连接
Connection getConnection() Connection getConnection(String username,String password)
//归还连接
Connection.close()

 

(2)常用的实现

  ①C3P0:使用此技术的有Hibernate、Spring等

  ②Druid:阿里巴巴实现

 

 

3. C3P0

  3.1 

(1)下载、导入jar

  官网:https://www.mchange.com/projects/c3p0/#installation

  导入:lib目录下的  c3p0-0.9.5.5.jar  mchange-commons-java-0.2.19  到项目依赖目录

(2)配置文件

  名称:c3p0.properties 或 c3p0-config.xml

  位置:放在src目录下即可

  c3p0.properties:

  c3p0.xml:

<c3p0-config>
  <!-- 使用默认的配置读取连接池对象 -->
  <default-config>
      <!--  连接参数 -->
    <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/dataBaseName?serverTimezone=UTC</property>
    <property name="user">root</property>
    <property name="password">root</property>
    
    <!-- 连接池参数 -->
    <property name="initialPoolSize">5</property>
    <property name="maxPoolSize">10</property>
    <property name="checkoutTimeout">3000</property>
  </default-config>

  <named-config name="otherc3p0"> 
    <!--  连接参数 -->
    <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/dataBaseName?serverTimezone=UTC</property>
    <property name="user">root</property>
    <property name="password">root</property>
    
    <!-- 连接池参数 -->
    <property name="initialPoolSize">5</property>
    <property name="maxPoolSize">8</property>
    <property name="checkoutTimeout">1000</property>
  </named-config>
</c3p0-config>

 

  3.2 相关类和接口

(1)ComboPooledDataSource

  

 

  3.3 简例

package com.jdbc;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class JdbcPoolC3P0 {
    public static void main(String[] args) {
        DataSource ds = new ComboPooledDataSource();
        Connection conn = null;
        Statement stmt = null;
        ResultSet result = null;
        try {
            conn = ds.getConnection();
            stmt = conn.createStatement();
            String sql = "select * from person";
            result = stmt.executeQuery(sql);

        } catch (SQLException throwables) {
            throwables.printStackTrace();
            System.out.println("获取连接失败");
        }finally {
            if(result != null) {
                try {
                    result.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
                result = null;
            }
            if(stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
                stmt = null;
            }
            if(conn != null) {
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
                conn = null;
            }

        }
    }
}

 

 

 

 

4. Durid

  4.1 下载导入jar

  导入:druid-version.jar

  4.2 配置

  任意名称的properties文件,可放在任意位置

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/testx?serverTimezone=UTC
username=root
password=root
initialSize=5
maxActive=10
maxWait=3000

 

  4.3  简单例子

//加载配置文件
Properties config = new Properties();
InputStream is = JdbcPoolDruid.class.getClassLoader().getResourceAsStream("druid.properties");
config.load(is);
//获取连接对象
DataSource dataSource = DruidDataSourceFactory.createDataSource(config);
Connection conn = dataSource.getConnection();

 

  4.4 优化

  工具类:将初始化数据库连接池、获取连接对象的方法封装

package com.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.jdbc.JdbcPoolDruid;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtils {
    private static DataSource dataSource;

    //初始化数据库连接池
    static {
        try {
            //加载配置文件
            Properties config = new Properties();
            InputStream is = JdbcPoolDruid.class.getClassLoader().getResourceAsStream("druid.properties");
            config.load(is);
            //获取DataSource
            dataSource = DruidDataSourceFactory.createDataSource(config);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取连接
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
    //释放资源
    public static void close(Statement stmt, Connection conn){
        close(null,stmt,conn);
    }

    public static void close(ResultSet result,Statement stmt,Connection conn) {
        if(result != null) {
            try {
                result.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(stmt != null) {
            try {
                stmt.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(conn != null) {
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    //获取连接池
    public static DataSource getDataSource(){
        return dataSource;
    }
}

 

 

  使用:

Connection conn = null;
Statement stmt = null;
ResultSet result = null;
try {
    conn = JDBCUtils.getConnection();
    stmt = conn.createStatement();
    String sql = "select * from person";
    result = stmt.executeQuery(sql);
} catch (SQLException throwables) {
    throwables.printStackTrace();
} finally {
    JDBCUtils.close(result,stmt,conn);
}

 

 

 

 

 

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Spring JDBC

  Spring框架对JDBC的简单封装,提供 JDBCTemplate对象简化JDBC开发

1. 步骤

  1.1 下载、导入jar

 

  1.2 创建 JdbcTemplate对象,依赖于数据源DataSource

DataSource ds = JDBCUtils.getDataSource();
JdbcTemplate template = new JdbcTemplate(ds);

  1.3 执行SQL

update() //增删改
queryForMap() //以Map方式返回结果
queryForList() //以List方式返回结果
query() //以JavaBean对象方式封装结果
queryForObject() 

 

 

2. 例子

  配置好Druid的配置文件,并使用已实现的JDBC工具类

DataSource ds = JDBCUtils.getDataSource();
JdbcTemplate template = new JdbcTemplate(ds);
String sql = "select * from person";
List<Map<String,Object>> list = template.queryForList(sql);
for(int i=0;i<list.size();i++) {
    Map<String,Object> map = list.get(i);
    for(String key:map.keySet()) {
        System.out.print(map.get(key)+"  ");
    }
    System.out.println();
}

 

posted @ 2020-05-26 06:41  T,X  阅读(127)  评论(0编辑  收藏  举报