简体   繁体   中英

NullPointerException when i try Select data from Mysql base

I have problem. When i try select data from database i see error NullPointerException. To connect to database i use Singleton pattern.

Singleton class :

public class Database {

private static Database instance = new Database();

private Connection con;

private Database() {

}

public static Database getInstance() {
    return instance;
}

public Connection getConnection(){
    return con;
}
public void connect() throws Exception {

    if (con != null)
        return;

    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        throw new Exception(e);
    }

    String url = String.format("jdbc:mysql://127.0.0.1:3306/newssystem");

    con = DriverManager.getConnection(url, "root","");
}

public void disconnect() {
    if (con != null) {
        try {
            con.close();
        } catch (SQLException e) {
            System.out.println("Nie można zakończyć połączenia");
        }
    }

    con = null;
}

}

Class to select data : public class ArtOpcje { public ArrayList getArtykul() throws SQLException {

    ArrayList<Artykul> news = new ArrayList<Artykul>();

    Connection conn = Database.getInstance().getConnection();

    String sql = "SELECT id, title, article FROM news";

    Statement pa = conn.createStatement();

    ResultSet results = pa.executeQuery(sql);

    while(results.next()) {                                     
        int id = results.getInt("id");
        String title = results.getString("title");
        String article = results.getString("article");
        Artykul artykul = new Artykul(id, title, article);  
        news.add(artykul);
    }
    results.close();
    pa.close();
    return news;
}
}

And code fragment when i use this Select in Combobox:

    combo.setBounds(150, 250, 350, 30);
    combo.removeAllItems();
    System.out.println("poza  pętlą");
    this.add(combo);

    ArrayList<Artykul> artykul = new ArrayList<Artykul>();
    artykul = art.getArtykul();


    String[] aa = new String[artykul.size()];
    for(int i =0; i<artykul.size(); i++){
         aa[i] = artykul.get(i).getTitle();
    }


Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
 at model.ArtOpcje.getArtykul(ArtOpcje.java:40)
 at view.View.<init>(View.java:82)
 at aplication.Aplication.runApp(Aplication.java:34)
 at aplication.Aplication$1.run(Aplication.java:21)
 at java.awt.event.InvocationEvent.dispatch(Unknown Source)
 at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
 at java.awt.EventQueue.access$500(Unknown Source)
 at java.awt.EventQueue$3.run(Unknown Source)
 at java.awt.EventQueue$3.run(Unknown Source)
 at java.security.AccessController.doPrivileged(Native Method)
 at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
 at java.awt.EventQueue.dispatchEvent(Unknown Source)
 at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
 at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
 at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
 at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
 at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
 at java.awt.EventDispatchThread.run(Unknown Source)

NullPointerException is here :

Statement pa = conn.createStatement();

If you closely look at the code, then you will realise the connection object is initialize inside connect method. But that method is never invoked in your code. Hence calling

Connection conn = Database.getInstance().getConnection();

Will return null instance of Connection Object. Instead you should use following code

Database db = Database.getInstance();
db.connect();
db.getConnection();

This should solve your problem.

Note: In ideal condition, you should make use of Connection pool or data source instead of writing your own JDBC code.

Thank you. Its work now.

    Database db;
    db = Database.getInstance();
    db.connect();
    db.getConnection();


    String sql = "SELECT id, title, article FROM news";

    PreparedStatement pa = db.getConnection().prepareStatement(sql);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM