Fork me on GitHub

JDBC和Druid

算是数据库实战篇简单实现篇,包括了安装MySQL,使用JDBC和数据库连接池。

参考视频学习数据库软件的使用。

同时参考了博客,作者写的很全面。

可视化工具SQLyog下载

MySQL

  1. 安装

  2. 卸载,要删除注册表,删除C:/ProgramData下的MySQL文件。

  3. 配置

    1. cmd==>services.msc打开服务窗口
    2. net stop mysql//以管理员身份打开cmd窗口
    3. net start mysql
  4. 登录

    1. mysql -uroot -pxxxx
    2. mysql -hip -uroot -pxxxx连接目标的密码(远程使用)
    3. mysql –host=ip –user=root –password=连接目标的密码
    4. 退出
      1. exit
      2. quit
    5. 目录结构
      1. 安装目录 my.ini数据库配置信息
      2. 数据目录
  5. 常用查询语句

    1
    2
    3
    4
    5
    6
    7
    8
    9
    show databases;
    show create database;
    create database if not exists db character set gbk;
    drop database if exists db;

    use db;
    select database();
    show tables;
    desc db;//表结构

问题汇总

  1. 在尝试Jdbc快速入门的时候遇到了class.forName(“com.mysql.jdbc.Driver”)加载失败,产生报错java.lang.ClassNotFoundException: com.mysql.jdbc.Driver,原因是同一个project建立了两个module时,第二个module并没有成功引入依赖jar包。解决方法,libs加入路径时搞错了。现在新版本不写class.forName()也可以通过,加了反而出错,原因不明。
  2. Access denied for user ''@'localhost' (using password: YES)常见错误,查看数据库连接配置的用户名和密码是否正确

JDBC

  • 使用步骤

    下载导入;注册驱动;获取连接对象Connection;定义sql;获取执行对象;执行sql,返回结果;处理结果;释放资源

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//1. 加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
//2. 建立连接
URL用于标识数据库的位置
Connection conn = DriverManager.getConnnection(url, user, pass);//通常存在配置文件中
//3.执行数据库语句
Statement st = conn.creatStatement();//向数据库发送连接的statement对象
String sql = "select id, name from student;"
int count = st.executeQuery(sql);
if(count){
System.out.println("成功创建");
}else{
System.out.println("创建失败");
}
conn.close();
st.close();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
UserService 
boolean register(User user);
boolean active(String code);
User login(User user);
UserServlet
register
login
active
findOne
exit
UserDao
User findByUsername(String username);
void save(User user);
User findByCode(String code);
void updateStatus(User user);
User findByUsernameAndPassword(String username, String password);

抽取JDBC工具类

  • 分析

    1. 注册驱动抽取 Class.forName()
    2. 抽取方法连接对象
    3. 抽取方法释放资源

    工具类静态方便调用

    静态代码块:在加载如内存的时候就执行了。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    public class JDBCUtils {
    private static String url;
    private static String username;
    private static String password;
    private static String driver;

    static{

    try {
    Properties prop = new Properties();
    //获取src路径下文件的方式
    ClassLoader classLoader = JDBCUtils.class.getClassLoader();
    URL res = classLoader.getResource("jdbc.properties");
    String path = res.getPath();
    prop.load(new FileReader(path));

    url = prop.getProperty("url");
    username = prop.getProperty("username");
    password = prop.getProperty("password");
    driver = prop.getProperty("driver");

    Class.forName(driver);//加载驱动
    } catch (IOException e) {
    e.printStackTrace();
    } catch (ClassNotFoundException e) {
    e.printStackTrace();
    }
    }
    /**
    * 获取连接
    * @return
    */
    public static Connection getConnection() throws SQLException {
    //字符串不能写死,采用配置文件解决
    return DriverManager.getConnection(url, username, password);
    }
    /**
    * 释放连接
    * @return
    */
    public static void close(Statement stmt, Connection conn, ResultSet rs){
    if(conn != null){
    try {
    conn.close();
    } catch (SQLException throwables) {
    throwables.printStackTrace();
    }
    }
    //不可以写一起,可能会漏掉,造成无法正常关闭
    if(stmt != null){
    try {
    stmt.close();
    } catch (SQLException throwables) {
    throwables.printStackTrace();
    }
    }
    if(rs != null){
    try {
    rs.close();
    } catch (SQLException throwables) {
    throwables.printStackTrace();
    }
    }
    }
    }

数据库连接池

存放数据库连接的容器,节约资源,用户访问高效。用户每次请求都需要向数据库获得链接,而数据库创建连接通常需要消耗相对较大的资源,创建时间也较长。假设网站一天10万访问量,数据库服务器就需要创建10万次连接,极大的浪费数据库的资源,并且极易造成数据库服务器内存溢出、宕机。

获取DataSource, 然后调用ds.getConnection()

C3P0

  • 使用
    1. 导入jar包和依赖jar包
    2. 定义配置文件 c3p0.properties or c3p0-config.xml,放在src目录下
    3. 创建核心对象 ComboPooledDataSource
    4. 获取连接
1
2
DataSource ds = new ComboPooledDataSource();//驱动程序提供厂商实现,可以通过它获取Connection对象
Connection conn = ds.getConnection;

Druid

  • 使用

    1. 导入jar包
    2. 定义配置文件 可以是任意名称在任意目录下
    3. 加载配置文件 Properties
    4. 获取数据库连接:通过工厂来获取 DruidDataSourceFactory
    5. 获取连接 getConnection
  • 定义工具类

    1. 提供静态代码块加载配置文件,初始化连接池对象
    2. 提供方法
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    public class druidUtils {
    //定义一个DataSource
    private static DataSource ds;

    static {

    try {
    //加载配置文件
    Properties prop = new Properties();
    prop.load(druidUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
    //获取DataSource
    ds = DruidDataSourceFactory.createDataSource(prop);
    } catch (IOException e) {
    e.printStackTrace();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    /**
    * 获取连接
    */
    public static Connection getConnection() throws SQLException {
    return ds.getConnection();
    }
    /**
    * 释放资源
    */
    public static void close(Statement stmt, Connection conn, ResultSet rs){
    if(stmt != null){
    try {
    stmt.close();
    } catch (SQLException throwables) {
    throwables.printStackTrace();
    }
    }
    if(conn != null){
    try {
    conn.close();
    } catch (SQLException throwables) {
    throwables.printStackTrace();
    }
    }
    if(rs != null){
    try {
    rs.close();
    } catch (SQLException throwables) {
    throwables.printStackTrace();
    }
    }
    }
    /**
    * 获取连接池
    */
    public static DataSource getDataSource(){
    return ds;
    }
    }

    配置文件druid.properties

    1
    2
    3
    4
    5
    6
    7
    driverClassName=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/db1
    username=root
    password=root
    initialSize=5
    maxActive=10
    maxWait=3000

Spring JDBC

  • Spring框架提供的对JDBC的简单封装
  • 步骤:
    1. 导入jar包
    2. 创建JdbcTemplate对象,依赖于DataSource
    3. 调用JdbcTemplate方法完成crud


本文标题:JDBC和Druid

文章作者:tsuki

发布时间:2022.03.22 - 21:47

最后更新:2022.03.22 - 22:11

原始链接:https://tsuki419.github.io/数据库II.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

-------------THE END-------------
0%