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个回答

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

把密码和用户名去了
url="jdbc:mysql://localhost:3306/mydatabase"
试试这样

setUserName() setPassWord();

运行提示unknown resource,看看"jbdc:mysql://localhost:3306/mydb?user=root&password=root&useUnicode=true&characterEncoding=UTF8";这句mydb是不是写错了

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐