首页 > 解决方案 > 数据库正在连接但未检索数据

问题描述

我正在尝试从数据库中创建一个简单的数据检索程序。连接成功,但我在控制台中收到此错误java.lang.ClassNotFoundException: com.mysql.jdbc.Driver Connection Successful

配置文件

 public class Config {

        public Connection connect() {
            Connection con = null;
            try {
                Class.forName("com.mysql.jdbc.Driver");

                con = DriverManager.getConnection("jdbc:mysql://localhost:3306/appointment", "root", "");
                System.out.println("Connection Successful");
            } catch (Exception e) {
                System.out.println("Connection unsuccessful");
                System.out.println("" + e);
            }

            return con;
        }
        public static void main(String[] args) {
        Config config = new Config();
        Connection con = config.connect();
        }

    }

调用数据库连接

public String readAppoinment() {
    String output = "";
    try {
        Connection con = config.connect();
        if (con == null) {
            return "Error while connecting to the database for reading appoinment details.";
        }
        output = "<table border=\"1\"><tr><th>Appointment Id</th><th>Appointment Date</th><th>Appointment Venue</th><th>Doctor Assign</th><th>Patient Id</th>"
                + "<th>Actions</th>";
        String query = "select * from appointment";
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(query);

        while (rs.next()) {
            String appId = Integer.toString(rs.getInt("app_Id"));
            String appDate = rs.getString("app_Date");
            String appVenue = rs.getString("app_Venue");
            String docId = Integer.toString(rs.getInt("app_Doctor_Id"));
            String patientId = Integer.toString(rs.getInt("app_Patient_Id"));

我正进入(状态

Error while connecting to the database

结果在浏览器中。

标签: javamysqlrestapijsp

解决方案


我相信问题在于这段代码。假设下面的代码在不同的类中。

public String readAppoinment() {
        String output = "";
        try {
            Connection con = Config.connect(); // This should properly called
            if (con == null) {
                return "Error while connecting to the database";
            }
}

推荐阅读