Java操作Mysql数据库的几种方式(一)-Mysql Connector/J组件

田普松
2023-12-01

环境准备

安装Mysql5.7

建议使用Docker方式安装和启动Mysql

安装Docker,如果已安装请忽略,这里是在Mac环境下安装的,其他环境类似

#brew cash install docker

下载Mysql镜像,这里下载的是5.7版本

#docker pull mysql:5.7

如果不加:5.7的参数,默认会下载最新的8.0版本

下载完成后,可以使用以下命令查看是否下载成功

#docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
mysql               5.7                 895f791fab9f        8 hours ago         435MB
mysql               latest              7a3923452254        8 hours ago         465MB

启动Mysql容器

#docker run -p 3306:3306 --name mysql -e MYSQL_ROOT_PASSWORD=password -d mysql:5.7

这样就可以简单的启动一个Mysql容器,启动过程支持多种参数,如果需要指定配置文件,如:

#docker run -p 3306:3306 --privileged=true -v /usr/local/docker/mysql/logs:/logs -v /usr/local/docker/mysql/data:/var/lib/mysql -v /etc/my.cnf:/etc/mysql/mysql.conf.d/mysqld.cnf -e MYSQL_ROOT_PASSWORD=password -d mysql:5.7

启动完成后,使用mysql命令测试

#mysql -h 127.0.0.1 -uroot -ppassword

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.29 MySQL Community Server (GPL)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 

表示Mysql可以正常使用了
在Mysql中创建用于测试的表

mysql>create database test;
Query OK, 1 row affected (0.01 sec)

使用Mysql Connector/J 连接mysql

介绍

Mysql为java语言提供了Connector/J组件用于连接和管理Mysql数据库,Connector/J实现了Java的JDBC接口API(参照Java JDBC4.2规范)。虽然Connector/J实现了数据库连接管理的功能,但在大型项目里,建议使用流行的持久化框架如Hibernate、Spring JDBC Templates、Mybatis SQL Maps等,可以简化JDBC编码量,降低维护、调试和安全成本。

安装Connector/J

安装Connector/J有如下几种方式

现在绝大部分项目都已经使用Maven进行管理,所以这里采用Maven安装的方式进行演示。对其他安装方式感兴趣可以自行根据上面的链接进行学习。

pom.xml中添加connector依赖

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.9-rc</version>
</dependency>

代码示例

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

// Notice, do not import com.mysql.cj.jdbc.*
// or you will have problems!

public class LoadDriver {
    public static void main(String[] args) {
        try {
            // The newInstance() call is a work around for some
            // broken Java implementations

            Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
        } catch (Exception ex) {
            // handle the error
        }
    }
}

获取一个连接

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

Connection conn = null;
...
try {
    conn =
       DriverManager.getConnection("jdbc:mysql://localhost/test?" +
                                   "user=minty&password=greatsqldb");

    // Do something with the Connection

   ...
} catch (SQLException ex) {
    // handle any errors
    System.out.println("SQLException: " + ex.getMessage());
    System.out.println("SQLState: " + ex.getSQLState());
    System.out.println("VendorError: " + ex.getErrorCode());
}

执行查询

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;

// assume that conn is an already created JDBC connection (see previous examples)

Statement stmt = null;
ResultSet rs = null;

try {
    stmt = conn.createStatement();
    rs = stmt.executeQuery("SELECT foo FROM bar");

    // or alternatively, if you don't know ahead of time that
    // the query will be a SELECT...

    if (stmt.execute("SELECT foo FROM bar")) {
        rs = stmt.getResultSet();
    }

    // Now do something with the ResultSet ....
}
catch (SQLException ex){
    // handle any errors
    System.out.println("SQLException: " + ex.getMessage());
    System.out.println("SQLState: " + ex.getSQLState());
    System.out.println("VendorError: " + ex.getErrorCode());
}
finally {
    // it is a good idea to release
    // resources in a finally{} block
    // in reverse-order of their creation
    // if they are no-longer needed

    if (rs != null) {
        try {
            rs.close();
        } catch (SQLException sqlEx) { } // ignore

        rs = null;
    }

    if (stmt != null) {
        try {
            stmt.close();
        } catch (SQLException sqlEx) { } // ignore

        stmt = null;
    }
}

其他

Mysql官方提供了详细的Connector/J的试用说明,包括安装连接选项和设置连接池多主机连接等,有兴趣可以学习一下。

 类似资料: