0

我是 java 和 JDBC 用法的新手。我正在编写我的第一个连接到数据库的 Java 应用程序。但是当我单击执行数据库创建的 JButton 时出现此错误。但我得到这个错误:

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

这是我的代码:

  $/** 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                   

}

这是与我的数据库通信的 DBOptions 类:

 $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
    }
}

}

请帮我...

4

1 回答 1

0

似乎抛出 NullPointerException 的行是这一行:

    Statement stmt = con.createStatement();

如果这是抛出 NullPointerException,那么您的静态变量con必须是null.

我看不到您正在创建数据库连接功能的任何地方connect()。据我所知,您收到错误是因为您在未连接到数据库时尝试在数据库中创建表。

或者,也许您正在调用connect()一些您选择不与我们共享的代码。在这种情况下,我猜您无法连接到数据库。但是,您方法中的以下代码connect()对于找出问题所在非常无用:

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

您的数据库连接失败的原因有很多,但是默默地吞下所有异常使得找出问题所在变得异常困难。e.printStackTrace();在该catch块中添加一行(在该return行之前),这将打印出导致数据库连接失败的异常。

于 2012-09-28T20:07:19.780 回答