Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8608761
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T03:41:55+00:00 2026-06-12T03:41:55+00:00

I am new to java and JDBC usage. I am writing my first java

  • 0

I am new to java and JDBC usage. I am writing my first java application that connects to database. But i am getting this error when i click on th JButton that performs database creation. But i get this error:

   $run:Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at data.eceunnrecords.com.DBOptions.executeNonQuery(DBOptions.java:70)
at portal.eceunnrecords.com.CreateDatabase.createButtonActionPerformed(CreateDatabase.java:81)
at portal.eceunnrecords.com.CreateDatabase.access$000(CreateDatabase.java:13)
at portal.eceunnrecords.com.CreateDatabase$1.actionPerformed(CreateDatabase.java:42)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6263)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6028)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4630)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4574)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2475)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

here is my code:

  $/** To change this template, choose Tools | Templates
  * and open the template in the editor.
  */
  package portal.eceunnrecords.com;
  import portal.eceunnrecords.com.*;
  import data.eceunnrecords.com.*;

 /**
  *
  * @author OPTHINKERS
  */
  public class CreateDatabase extends javax.swing.JFrame {

/**
 * Creates new form CreateDatabase
 */
public CreateDatabase() {
    initComponents();
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jLabel1 = new javax.swing.JLabel();
    createdbtf = new javax.swing.JTextField();
    createButton = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel1.setText("Database Name:");

    createButton.setText("Create");
    createButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            createButtonActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(78, 78, 78)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addComponent(createButton)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jLabel1)
                    .addGap(18, 18, 18)
                    .addComponent(createdbtf, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap(144, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(110, 110, 110)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel1)
                .addComponent(createdbtf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(18, 18, 18)
            .addComponent(createButton)
            .addContainerGap(129, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>                        

private void createButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
    // TODO add your handling code here:
    String query = "Create Table "+this.createdbtf.getText()+"(REG_NO VARCHAR (10)"
            + "NOT NULL PRIMARY KEY, SURNAME VARCHAR (45) NOT NULL, FIRSTNAME VARCHAR (45) "
            + "NOT NULL, MIDDLENAME VARCHAR (45) NOT NULL, LEVEL INT NOT NULL, STATE_OF_ORIGIN "
            + "VARCHAR (25) NOT NULL, PHONE_NO INT NOT NULL, EMAIL VARCHAR (50) NOT NULL);";
    DBOptions.executeNonQuery(query);
}                                            

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /*
     * Set the Nimbus look and feel
     */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /*
     * If Nimbus (introduced in Java SE 6) is not available, stay with the
     * default look and feel. For details see
     * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(CreateDatabase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(CreateDatabase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(CreateDatabase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(CreateDatabase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /*
     * Create and display the form
     */
    java.awt.EventQueue.invokeLater(new Runnable() {

        public void run() {
            new CreateDatabase().setVisible(true);
        }
    });
}
// Variables declaration - do not modify                     
private javax.swing.JButton createButton;
private javax.swing.JTextField createdbtf;
private javax.swing.JLabel jLabel1;
// End of variables declaration                   

}

And here is the class DBOptions that communicates with my database:

 $package data.eceunnrecords.com;
  import java.sql.*;
  import javax.swing.*;


  public class DBOptions {
 /**
 * static variable con is used to hold the active connection information.
 */
 public static Connection con = null;
/**
 *This method is used to make a connection with the database
 * @param strHost holds host name or ip address
 * @param iPort holds port number
 * @param strDBName holds the database name
 * @param strUserName holds username to connect to server
 * @param strPassword holds password to connect to server
 * @return true for establishing connection and false for failure.
 */
public static boolean connect(String strHost, int iPort,String strDBName, String strUserName, String strPassword)
{
    try
    {
        //loading mysql jdbc driver
        Class.forName("com.mysql.jdbc.Driver");
        //connection string
        String url="jdbc:mysql://"+strHost+":"+iPort+"/"+strDBName;
        //establishing connection
        con=DriverManager.getConnection(url, strUserName,strPassword);
        return true; //successfully connected
    }
    catch(Exception e)
    {
        return false; //connection failed
    }
}
/**
 * This method is used to close the database connection
 * @param dbCon holds the active connection information
 */
public static void closeConnection(Connection dbCon)
{
    try
    {
        dbCon.close(); //close connection
    }
    catch(Exception e)
    {

    }
}
/**
 * This method is used to execute an sql non query
 * @param sqlString holds the sql non query to be executed
 * @return the number of rows affected
 */
public static int executeNonQuery(String sqlString)
{
    try
    {
        Statement stmt = con.createStatement();
        return stmt.executeUpdate(sqlString);
        //return the number of rows affected
    }
    catch(SQLException e)
    {
        //display error message
        //JOptionPane.showMessageDialog(null,  e.getMessage()+"\nPlease Try Again","Non Query Execution Failure", 1);
        return -1;
    }
}
/**
 * This method is used to execute an sql query
 * @param sqlQuery holds the sql query
 * @return the ResultSet if successful. Return null on failure
 */
public static ResultSet executeSQLQuery(String sqlQuery)
{
    try
    {
        Statement stmt = con.createStatement();
        return stmt.executeQuery(sqlQuery); //query successfully executed
    }
    catch(SQLException e)
    {
        //display error message
        //JOptionPane.showMessageDialog(null, e.getMessage()+"\nPlease Try Again","Query Execution Failure", 1);
        return null; //sql query execution failed
    }
}

}

please help me…

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T03:41:56+00:00Added an answer on June 12, 2026 at 3:41 am

    It seems that the line that is throwing the NullPointerException is this line:

        Statement stmt = con.createStatement();
    

    If this is throwing a NullPointerException, then your static variable con must be null.

    I can’t see anywhere where you are creating your database connection function connect(). As far as I can see, you’re getting the error because you’re trying to create a table in a database when you’re not connected to the database.

    Alternatively, perhaps you are calling connect() in some code you’ve chosen not to share with us. In which case, I’d guess that you are failing to connect to the database. However, the following code within your connect() method is extremely unhelpful when it comes to finding out what went wrong:

    catch(Exception e)
    {
        return false; //connection failed
    }
    

    There are numerous different reasons why your database connection might be failing, but silently swallowing all exceptions makes it incredibly difficult to find out what is going wrong. Add a line e.printStackTrace(); to this catch block (before the return line) and that will print out the exception that is causing the database connection to fail.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am writing a Java JDBC database application that connects to an Oracle 11g
how to connect mysql database to desktop java application using jdbc ? the environment
I have a Java JDBC application that uses multiple threads to retrieve information from
I'm pretty new to Java, and I'm writing a program that needs to store:
When I start a new Java project in eclipse, the first popup screen allow
I am starting a new Java web project that will be worked on by
We are starting a new java web-project with Cassandra as the database. The team
My program needs to represent this date as a java.sql.date object , but it
I'm new to java and trying to write a simple program using JDBC. It
I am fetching records from MySQL database using Java (JDBC). I have tables -

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.