You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java连接本地MySQL数据库抛出异常如何修复代码?

问题修复方案
  • JDBC URL拼写错误:你写的jdbc:mqsql://localhost:3306/siba_1中mqsql拼写错误,正确应为mysql
  • 异常捕获逻辑错误:catch块中仅打印了字符串"e",无法输出实际异常堆栈信息,不利于排查问题
  • 驱动类适配问题:若使用MySQL 8.0及以上版本,旧驱动类com.mysql.jdbc.Driver已被废弃,需替换为com.mysql.cj.jdbc.Driver,同时URL需补充时区、SSL等参数避免报错
  • 资源未释放:Connection、Statement、ResultSet使用完成后未关闭,会导致JDBC资源泄漏

修正后的完整代码

package java_recap;
import java.sql.*;

public class Java_recap {   
    public static void main(String[] args) {
        Connection con = null;
        Statement stn = null;
        ResultSet rs = null;
        try{
            // MySQL 5.x版本可以保留旧驱动类 com.mysql.jdbc.Driver
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 修正URL拼写,补充时区和SSL参数
            con=DriverManager.getConnection("jdbc:mysql://localhost:3306/siba_1?useSSL=false&serverTimezone=Asia/Shanghai","root","你的MySQL root账号密码");
            stn=con.createStatement();
            rs=stn.executeQuery("select * from test_1");
            while(rs.next()){
                System.out.println(rs.getString(1)+" "+rs.getString(2));
            }
        } catch(Exception e){
            // 打印实际异常堆栈,方便定位问题
            e.printStackTrace();
        } finally {
            // 逆序释放资源
            try { if(rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); }
            try { if(stn != null) stn.close(); } catch (SQLException e) { e.printStackTrace(); }
            try { if(con != null) con.close(); } catch (SQLException e) { e.printStackTrace(); }
        }
    }
}

额外注意事项

  • 确认本地MySQL服务已正常启动,3306端口未被占用
  • 确认root账号的密码填写正确,若未设置密码可保留空字符串
  • 确认siba_1数据库、test_1表已存在,且root账号拥有该库的查询权限

内容的提问来源于stack exchange,提问作者Mithun Deshan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 15:09:02