Unknown database ‘xxxxx‘

1、问题描述

今天在回顾jdbc连接mysql的时间遇到了一个报错,Unknown database ‘xxxxx’
如图:
在这里插入图片描述

public class JDBCConnectMySQL {
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://127.0.0.1:3306/studysql?useSSL=false&useUnicode=true&characterEncoding=UTF-8";
    static final String USER = "root";
    static final String PASSWORD = "root";
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            //1.注册驱动
            Class.forName(JDBC_DRIVER);
            // 提供jdbc的url
            //2.创建数据库连接
            connection = DriverManager.getConnection(DB_URL, USER, PASSWORD);
            //3.创建statement实例
            String sql = "select * from dept";
            preparedStatement = connection.prepareStatement(sql);
            //4.执行sql语句
            resultSet = preparedStatement.executeQuery(sql);
            //5.处理结果集
            while (resultSet.next()){
                int id = resultSet.getInt("id");
                String deptName = resultSet.getString("name");
                String loc = resultSet.getString("money");

                System.out.print("id: " + id);
                System.out.print("deptName: " + deptName);
                System.out.println("loc: " + loc);
            }
            //6.关闭jdbc对象 先开后关
            resultSet.close();
            preparedStatement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //安全起见,在finally里关闭资源,先判断是否为null
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }

        }

    }
}

2、可能的原因

  1. 数据库名错误,仔细检查数据库名
  2. 检查Java代码,数据库配置的url中库名称与数据库是否一致

3、解决

我的原因是这个数据库是我自己很久以前自己建的,用来练习的,不小心前面数据库前面多了个空格
把数据库的名字改一下就好了

单独看或许看不出来,比较一下就很明显了
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值