idea2020使用JDBC连接mysql数据库

首先打开模块化设置
在这里插入图片描述
在这里添加相应的.jar包
在这里插入图片描述
然后会得到这样的一个结果
在这里插入图片描述
接着就可以进行测试了,在测试样例中我结合了配置文件一起使用的
配置文件.properties

DRIVER_HOME=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/chencj?characterEncoding=utf-8&serverTimezone=UTC
user=root
password=自己设置的密码
import java.sql.*;
import java.util.ResourceBundle;

public class selectSalgrade {
    public static void main(String[] args) {
        ResourceBundle bundle = ResourceBundle.getBundle("配置文件");

        String DRIVER_HOME = bundle.getString("DRIVER_HOME");
    //    System.out.println(DRIVER_HOME);
        String url = bundle.getString("url");
        String user = bundle.getString("user");
        String password = bundle.getString("password");

        Connection conn = null;
        Statement statement = null;
        ResultSet rs = null;
        try {
            //1.加载驱动
            Class.forName(DRIVER_HOME);
            //2.创建连接
            conn = DriverManager.getConnection(url,user,password);
            //3.写SQL语句
            String sql = "select * from salgrade";
            //4.获取执行SQL的statement对象
            statement = conn.createStatement();
            //5.执行select返回结果
            rs = statement.executeQuery(sql);

            System.out.println("============================");
            while(rs.next()){
                System.out.print(rs.getInt(1) + ",");
                System.out.print(rs.getString(2) + ",");
                System.out.println(rs.getString(3));
            }
            System.out.println("============================");

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            //6.关闭连接
            if(rs != null) {
                try {
                    rs.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }

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

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

测试结果
在这里插入图片描述


版权声明:本文为chenchanghie原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。