简体   繁体   中英

NullPointerException while inserting data into java db

For the past 3 hours, i tried lots of code to get rid of the error i faced while inserting data to the java db(derby). please suggest me a correct solution. after clicking the addButton, data is not inserted into the db. it shows the following error. plsease suggest me some idea.

Gui Class:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import net.miginfocom.swing.*;
import javax.swing.border.*;
import javax.swing.BorderFactory;
import java.sql.*;
import java.util.*;
public class Gui { 
    JFrame frame;
    JPanel mainPanel;
    JPanel addPanel;
    JPanel wordsPanel;
    JPanel randomPanel;
    JPanel wordTestPanel;
    JTextField wordNameField;
    JTextField wordMeaningField;
    JLabel DialogLabel;
    MigLayout layout;
    TitledBorder title;

    public static void main(String[] args) { 
        Gui gui = new Gui();
        gui.showFrame();
    } 

    public void showFrame() { 
        frame = new JFrame("My Words");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        layout = new MigLayout();
        Container content = frame.getContentPane();
        content.add(showMainPanel());
        frame.pack();
        frame.setVisible(true); 
    } 

    public JPanel showMainPanel() { 
        mainPanel = new JPanel();
        mainPanel.setLayout(layout);
        mainPanel.add(showAddPanel(),"wrap");
        mainPanel.add(showRandomPanel(),"wrap");
        mainPanel.add(showWordTestPanel(),"wrap");
        mainPanel.add(showWordsPanel(),"east");

        return mainPanel;
    } 

    public JPanel showAddPanel() { 
        addPanel = new JPanel();
        addPanel.setLayout(layout);
        title = BorderFactory.createTitledBorder("Add Word");
        title.setTitleJustification(TitledBorder.RIGHT);
        addPanel.setBorder(title);
        JLabel wordNameLabel = new JLabel("Word Name: ");
        JLabel wordMeaningLabel = new JLabel("Word Meaning: ");
        wordNameField = new JTextField(20);
        wordMeaningField = new JTextField(20);
        JButton addButton = new JButton("Add");
        addButton.addActionListener(new addButtonListener());
        JButton clearButton = new JButton("Clear");
        DialogLabel = new JLabel(".");
        addPanel.add(wordNameLabel,"align label");
        addPanel.add(wordNameField,"wrap");
        addPanel.add(wordMeaningLabel,"align label");
        addPanel.add(wordMeaningField,"wrap");
        addPanel.add(addButton,"span 2");
        addPanel.add(clearButton,"span 2,wrap");
        addPanel.add(DialogLabel,"span");

        return addPanel; 
    } 

    public JPanel showRandomPanel() { 
        randomPanel = new JPanel();
        randomPanel.setLayout(layout);
        title = BorderFactory.createTitledBorder("Random Words");
        title.setTitleJustification(TitledBorder.RIGHT);
        randomPanel.setBorder(title);
        JLabel wordName = new JLabel("Hello");
        JLabel wordMeaning = new JLabel("this is the meaning");
        randomPanel.add(wordName,"wrap");
        randomPanel.add(wordMeaning,"span");

        return randomPanel; 
    } 

    public JPanel showWordTestPanel() { 
        wordTestPanel = new JPanel();
        wordTestPanel.setLayout(layout);
        title = BorderFactory.createTitledBorder("Word Test");
        title.setTitleJustification(TitledBorder.RIGHT);
        wordTestPanel.setBorder(title); 

        return wordTestPanel;
    } 

    public JPanel showWordsPanel() {
        wordsPanel = new JPanel();
        wordsPanel.setLayout(layout);
        title = BorderFactory.createTitledBorder("List of Words");
        title.setTitleJustification(TitledBorder.RIGHT);
        wordsPanel.setBorder(title);

        return wordsPanel;
    } 

    class addButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            String word = wordNameField.getText();
            String meaning = wordMeaningField.getText();
            Connection conn = null;
            Statement stmt = null;
            try {
                JDBCUtil.getConnection();
                stmt = conn.createStatement();
                String SQL; SQL = "INSERT INTO words(wordName,wordMeaning) VALUES(" + word + "," + meaning + ")";
                stmt.executeUpdate(SQL);
            } catch(SQLException se) {
                se.printStackTrace();
            } finally {
                JDBCUtil.closeStatement(stmt);
                JDBCUtil.closeConnection(conn);
            }
        }
    }
}

JDBCUtil class:

import java.sql.*;

public class JDBCUtil {
    public static Connection getConnection() throws SQLException {
        Driver derbyEmbeddedDriver = new org.apache.derby.jdbc.EmbeddedDriver();
        DriverManager.registerDriver(derbyEmbeddedDriver);
        String dbURL = "jdbc:derby:mywords;create = true;";
        Connection con = DriverManager.getConnection(dbURL);
        con.setAutoCommit(false);

        return con;
    }

    public static void closeConnection(Connection con) {
        try {
            if(con != null) {
                con.close();
            }
        } catch(SQLException e) {
            e.printStackTrace();
        }
    }

    public static void closeStatement(Statement stmt) {
        try {
            if(stmt != null) {
                stmt.close();
            }
        } catch(SQLException e) {
            e.printStackTrace();
        }
    }

    public static void closeResultSet(ResultSet rs) {
        try {
            if(rs != null) {
                rs.close();
            }
        } catch(SQLException e) {
            e.printStackTrace();
        }
    }

    public static void commit(Connection con) {
        try {
            if(con != null) {
                con.commit();
            }
        } catch(SQLException e) {
            e.printStackTrace();
        }
    }

    public static void rollback(Connection con) {
        try {
            if(con!=null) {
                con.rollback();
            }
        } catch(SQLException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Connection con = null;
        try {
            con = JDBCUtil.getConnection();
            System.out.println("Connected to the Database");
        } catch(SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.closeConnection(con);
        }
    }
}

Error:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at Gui$addButtonListener.actionPerformed(Gui.java:114)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:20 18)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.jav a:2341)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259 )
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6505)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3320)
    at java.awt.Component.processEvent(Component.java:6270)
    at java.awt.Container.processEvent(Container.java:2229)
    at java.awt.Component.dispatchEventImpl(Component.java:4861)
    at java.awt.Container.dispatchEventImpl(Container.java:2287)
    at java.awt.Component.dispatchEvent(Component.java:4687)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832 )
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
    at java.awt.Container.dispatchEventImpl(Container.java:2273)
    at java.awt.Window.dispatchEventImpl(Window.java:2719)
    at java.awt.Component.dispatchEvent(Component.java:4687)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735)
    at java.awt.EventQueue.access$200(EventQueue.java:103)
    at java.awt.EventQueue$3.run(EventQueue.java:694)
    at java.awt.EventQueue$3.run(EventQueue.java:692)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
    at java.awt.EventQueue$4.run(EventQueue.java:708)
    at java.awt.EventQueue$4.run(EventQueue.java:706)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:705)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

You get your connection, but you don't store a reference to it, so conn remains null.

Try doing

conn = JDBCUtil.getConnection();

At least, that's what I could work out through the formatting.

Connection conn = null;
JDBCUtil.getConnection();
stmt = conn.createStatement();

conn is always null in this scenario.

Set conn to JDBCUtil.getConnection(); like conn = JDBCUtil.getConnection();

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