Как извлечь элементы из базы данных в программу JDB C - PullRequest
0 голосов
/ 17 января 2020

Я попробовал базовую c программу для извлечения данных из таблицы базы данных в java программу. В конце компиляции при запуске кода возникает исключение. Ошибка не отображается в консоли. Он отображает сообщение об исключении

import java.sql.*;
public class class1 {
    public static void main(String args[]){
        String url = "jdbc:mysql://localhost:3306//orders";
        String username = "root";
        String password = "Luxan@22";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection(url, username, password);
            Statement st = con.createStatement();
            ResultSet rs =  st.executeQuery("SELECT CUST_NAME FROM CUSTOMERS");
            System.out.println("List of Registered customers: ");
            while(rs.next()){
                System.out.println(rs.getString("cust_name"));
            }
            st.close();
            con.close();
        }
        catch(Exception e){
            System.out.println("An Exception error occured while processing JDBC programme");
        }
    }
}

Ниже вывод получен в моем окне консоли

Fri Jan 17 19:34:24 IST 2020 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

An Exception error occured while processing JDBC programme

Ответы [ 3 ]

1 голос
/ 17 января 2020

Проблема с вашим URL. Замените

"jdbc:mysql://localhost:3306//orders"

на

"jdbc:mysql://localhost:3306/orders"

Обратите внимание, что я удалил одну / до orders.

0 голосов
/ 17 января 2020

Трудно увидеть, что пошло не так, не зная структуру вашей таблицы. Но вот еще один способ написания вашей программы. Возможно, это поможет вам приблизиться к цели:

public class Class1 {

    public static void main(String[] args) {

        try {
            Class.forName("com.mysql.jdbc.Driver");   // this line is optional since Java 1.6 Normally for MySQL you shouldn't have to do this
            // This is called "try-with-resources". It means that inside your "try" declaration you
            // tell Java what things you want to open (here you wnat to open a connection)
            // and it will automatically close any connection (on failure or success) for you
            try (
                    Connection connection = DriverManager.getConnection(
                            "jdbc:mysql://localhost:3306/orders", // before the database name there is only one /
                            "root", // the database user
                            "password"); // the password
                    Statement statement = connection.createStatement() // the same try-with resources can open the statement for your
                    ) {

                ResultSet rs = statement.executeQuery("SELECT CUST_NAME FROM CUSTOMERS");
                while (rs.next()) {
                    System.out.println(rs.getString("cust_name"));
                }

            } catch (SQLException ex) {
                Logger.getLogger(Class1.class).log(Level.SEVERE, null, ex);   // this will properly log your SQLException. Don't be afraid, SQL error messages are scary and Java Exceptions are impressive. But they will tell you where the problem is
            }
        } catch (ClassNotFoundException ex) {   // if you register your driver you need to catch the exception as well
            Logger.getLogger(Class1.class).log(Level.SEVERE, null, ex);
        }
    }
}

Подробнее об этом примере можно прочитать на MkYong .

Надеюсь, это поможет вам.

Еще одна вещь:

Имена классов начинаются с заглавной буквы: Class1 вместо class1. Потому что имена переменных начинаются с маленькой буквы. Представьте, что вы хотите создать экземпляр класса с именем car. Тогда вы скажете car car = new car();, что невозможно прочитать. Car car = new Car() однако ясно:)

0 голосов
/ 17 января 2020

Попробуйте добавить ?useSSL=false в конец URL соединения.

...