转载

连接MySQL(maven)

<dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.11</version>
     </dependency>
复制代码

2、新建properties文件保存连接信息

url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
username=root
password=
复制代码

3、utils包中创建工具类

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class MysqlUtil {
    /**
     * 创建数据库连接
     * @return
     * con 数据库连接
     */
    public static Connection getConnection() {
        Connection con=null;
        try {
            //加载属性文件,读取数据库连接配置信息
            Properties pro = new Properties();
            try {
                InputStream in=MysqlUtil.class.getClassLoader().getResourceAsStream("mysql.properties");
                pro.load(in);
            } catch (IOException e) {
                System.out.println("未找到配置文件!!!");
            }
            String url = pro.getProperty("url");
            String username = pro.getProperty("username");
            String password = pro.getProperty("password");
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection(url, username, password);// 创建数据连接
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("数据库连接失败");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("驱动类找不到");
        }
        return con;
    }


    /**
     * 关闭数据库
     * @param con
     * @param stm
     * @param rs
     */
    public static void close(Connection con, Statement stm, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stm != null) {
            try {
                stm.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

复制代码

4、在数据库中创建测试库并编写测试程序

import java.sql.*;

public class test_sql {
    public static void main(String[] args) {
        Connection con = null;
        Statement stm = null;
        ResultSet rs = null;
        try {
            con = MysqlUtil.getConnection();
            String sql = "SELECT * FROM test_user";
            stm = con.createStatement();
            rs = stm.executeQuery(sql);
            System.out.println("查询结果:");
            while (rs.next()) {
                String name = rs.getString("name");
                System.out.println(name);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MysqlUtil.close(con, stm, rs);
        }
    }
    }
复制代码
原文  https://juejin.im/post/5e9aeda1e51d4546f63099f7
正文到此结束
Loading...