简体   繁体   English

我尝试从Mysql base选择数据时出现NullPointerException

[英]NullPointerException when i try Select data from Mysql base

I have problem. 我有问题。 When i try select data from database i see error NullPointerException. 当我尝试从数据库中选择数据时,我看到错误NullPointerException。 To connect to database i use Singleton pattern. 要连接到数据库,我使用Singleton模式。

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 { 选择数据的类:公共类ArtOpcje {公共ArrayList getArtykul()引发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: 和代码片段,当我在Combobox中使用此Select时:

    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 : NullPointerException在这里:

Statement pa = conn.createStatement();

If you closely look at the code, then you will realise the connection object is initialize inside connect method. 如果仔细看一下代码,那么您会发现connection对象是在connect方法中初始化的。 But that method is never invoked in your code. 但是该方法永远不会在您的代码中调用。 Hence calling 因此打电话

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

Will return null instance of Connection Object. 将返回Connection对象的空实例。 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. 注意:在理想情况下,应该使用连接池或数据源,而不是编写自己的JDBC代码。

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我尝试从getter获取数据时,为什么会出现NullPointerException? - Why am I getting a NullPointerException when I try to get data from a getter? 当我尝试运行Struts Dispatcher时出现NullPointerException - NullPointerException when I try to run Struts Dispatcher 每当我尝试在mysql数据库中插入数据时(在springboot java上),自动装配的存储库都会收到nullPointerException错误 - Autowired repository gets a nullPointerException error everytime i try to insert data in mysql database (on springboot java) 尝试从网络摄像头捕获imagem时发生NullPointerException - NullPointerException when try to capture imagem from webcam 活动之间的Android可打包数据。 尝试读取数据时获取NullPointerException - Android parcelable data between activities. Getting NullPointerException when I try to read data 当我尝试从数据库Derby DB中选择数据时出现奇怪的错误 - Strange error when I try to select data from database Derby DB 当我尝试在android中的片段之间获取数据时出现java.lang.NullPointerException - java.lang.NullPointerException when I try to get Data between fragments in android 当我尝试用数据库数据填充Java Swing中的表时出现java.lang.NullPointerException错误消息 - java.lang.NullPointerException error message when I try to populate table in java swing with database data 尝试保存图像时为什么会出现NullPointerException? - Why am i getting NullPointerException when i try to save image? 无法从MySQL数据库中选择数据:java.lang.NullPointerException - Can't select data from MySQL database: java.lang.NullPointerException
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM