Không thể kết nối database với java

và code java:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dictionary.core;

/**
 *
 * @author think
 */
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class MySQLConnect 
{
    private final String className = "com.mysql.cj.jdbc.Driver";
    private final String url = "jdbc:mysql://localhost:3306/mydb?autoReconnect=true&useSSL=false";
    private final String user = "root";
    private final String pass = "password";
    private final String table = "keyword";
    private Connection connection;
    
    private void Connect() throws SQLException
    {
        try 
        {
            Class.forName(className);
            connection = DriverManager.getConnection(url,user,pass);
            System.out.println("success");
        } catch (ClassNotFoundException ex) {
             System.out.println(ex.toString());
        } catch (SQLException e)
        {
             System.out.println(e.toString());
        }
        
    }
    private ResultSet getData()
    {
        ResultSet rs = null;
        String sqlCommand = "select * from " + table;
        Statement st;
        try
        {
            st = connection.createStatement();
            st.executeQuery(sqlCommand);
        } catch(SQLException e)
        {
            e.printStackTrace();
        }
        return rs;
    }
    private void showData(ResultSet rs)
    {
        try
        {
            while(rs.next())
            {
                System.out.printf("%10s %10s \n", rs.getString(1), rs.getString(2));
            }
        } catch(SQLException e)
        {
            e.printStackTrace();
        }
    }
        
    public static void main(String[] args) throws SQLException
    {
        MySQLConnect myconnect = new MySQLConnect();
        myconnect.Connect();
        myconnect.showData(myconnect.getData());
    }
   
}

nhưng khi run nó báo:

Exception in thread “main” java.lang.NullPointerException
at com.dictionary.core.MySQLConnect.showData(MySQLConnect.java:59)
at com.dictionary.core.MySQLConnect.main(MySQLConnect.java:73)
C:\Users\think\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)

Ổn cả, chỉ trừ không gán kết quả sau khi truy vấn thôi.
Gợi ý:

    private ResultSet getData()
    {
        ResultSet rs = null; // Ở đây...
        String sqlCommand = "select * from " + table;
        Statement st;
        try
        {
            st = connection.createStatement();
            st.executeQuery(sqlCommand); // ...Và đây
        } catch(SQLException e)
        {
            e.printStackTrace();
        }
        return rs;
    }
2 Likes
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?