SainPortman 2017-12-01 06:23 采纳率: 100%
浏览 2058
已采纳

java连接MySQL数据库总是提示连接失败,cmd可以读取数据库内容,驱动包也已载入

import java.sql.*;
import java.util.*;

class Student{
    String sno;
    String name;
    public Student(String sno, String name) {
        super();
        this.sno = sno;
        this.name = name;

    }
    @Override
    public String toString() {
        return "Student [sno=" + sno + ", name=" + name + "]";
    }
}

public class TestJDBC {
public static void main(String[] args) {
Connection con=null;
try{
Class.forName("com.mysql.jdbc.Driver");
String url="jbdc:mysql://localhost:3306/mydb?user=root&password=root&useUnicode=true&characterEncoding=UTF8";
con=DriverManager.getConnection(url);
System.out.println("连接成功!");

    }catch(ClassNotFoundException e){
        System.out.println("载入JDBC驱动类出错");
        e.printStackTrace();
        return;
    }catch(SQLException e){
        System.out.println("创建数据库连接出错");
        e.printStackTrace();
        return;
    }
    Statement stmt=null;
    ResultSet rs=null;
    List<Student> studentList=new ArrayList();
    try {
        String sql="Select * from student";
        stmt=con.createStatement();
        rs=stmt.executeQuery("mydatabase");
        while(rs.next()) {
            String sno=rs.getString("sno");
            String name=rs.getString("name");
            Student student=new Student(sno,name);
            studentList.add(student);
        }
    }catch(SQLException e) {
        System.out.println("查询数据库出错");
        e.printStackTrace();
    }finally {
        try {
            rs.close();
            stmt.close();
            con.close();
        }catch(SQLException e) {
            System.out.println("关闭资源出错");
            e.printStackTrace();
            rs=null;
            stmt=null;
            con=null;
        }
    }
    for (Student student:studentList){
        System.out.println(student);
    }
}

}
图片说明

  • 写回答

4条回答 默认 最新

  • diyword 2017-12-01 06:45
    关注

    rs=stmt.executeQuery("mydatabase");这句不是应该是rs=stmt.executeQuery(sql);

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名