java - 写入数据库表

标签 java sql database file-io

我正在尝试将新记录写入两个数据库表,分别称为itemsupplier

我有一个处理数据库连接和 SQL 语句的类。我在名为 ItemEntryScreen 的类中使用大型表单,我在其中使用以下内容:

private void writeItemRecord()
{
     if ( DataBaseHandler.makeConnectionTofireplaceDB() == -1)
       {
           JOptionPane.showMessageDialog (frame, "Unable to connect to database table (Item)");
       }
     else  // Ok, so first read data from the text fields
       {
           // Read data from form and store data     
           String suppliercode = suppliercodeTxtField.getText();
           String suppliername = suppliernameTxtField.getText();
           String address = addressTxtField.getText();


           // Create a Item oject
           Item item = new Item();

           // Set the attributes for the Item object
           item.setSuppliercode(suppliercode);
           item.setSuppliername(suppliername);
           item.setAddress(address);

           // Write Item record.  Method writeToItemTable() returns
           // 0 of OK writing record, -1 if there is a problem.  I store
           // the returned value in a variable called error.
           int error = DataBaseHandler.writeTosupplierTable(item.getSuppliercode(),item.getSuppliername(),item.getAddress());

           // Check if there is a problem writing the record, in 
           // which case error will contain -1                                         
           if (error == -1)
             {
                 JOptionPane.showMessageDialog (frame, "Problem writing record to Item Table");
             }

          // Clear the form - actual method is coded below
          clearForm();

          // Close database connection.  Report an error message
          // if there is a problem.
          if ( DataBaseHandler.closeConnection() == -1 )
             {
                 JOptionPane.showMessageDialog (frame, "Problem closing data base conection");
             }
        }
    }                    

/**
 *  Method to write a Item record
*/
private void writesupplierRecord()
{
     // Check to see if we can connect to database table
     if ( DataBaseHandler.makeConnectionTofireplaceDB() == -1)
       {
           JOptionPane.showMessageDialog (frame, "Unable to connect to database table (Item)");
       }
     else  // Ok, so first read data from the text fields
       {
           // Read data from form and store data     

           String itemname = itemnameTxtField.getText();
           String itemcode = itemcodeTxtField.getText();
           String description = descriptionTxtField.getText();
           String unitprice = unitpriceTxtField.getText();
           String style = styleTxtField.getText();
           String finish = finishTxtField.getText();
           String stock = stockTxtField.getText();

           // Convert priceStr to a float
           Float fvar = Float.valueOf(unitprice);
           float newprice = fvar.floatValue();

           Float svar = Float.valueOf(stock);
           float newstock = svar.floatValue();

           // Create a Item oject
           Item item = new Item();

           // Set the attributes for the Item object
           item.setItemname (itemname);
           item.setItemcode (itemcode);
           item.setDescription (description);
           item.setUnitprice (newprice);
           item.setStock(newstock);
           item.setStyle(style);
           item.setFinish(finish);

           // Write Item record.  Method writeToItemTable() returns
           // 0 of OK writing record, -1 if there is a problem.  I store
           // the returned value in a variable called error.
           int error = DataBaseHandler.writeToitemTable(item.getItemname(),
                                                        item.getItemcode(),
                                                        item.getDescription(),
                                                        item.getUnitprice(), 
                                                        item.getStock(),
                                                        item.getStyle(),
                                                        item.getFinish()
                                                        );

           // Check if there is a problem writing the record, in 
           // which case error will contain -1                                         
           if (error == -1)
             {
                 JOptionPane.showMessageDialog (frame, "Problem writing record to Item Table");
             }

          // Clear the form - actual method is coded below
          clearForm();

          // Close database connection.  Report an error message
          // if there is a problem.
          if ( DataBaseHandler.closeConnection() == -1 )
             {
                 JOptionPane.showMessageDialog (frame, "Problem closing data base conection");
             }
        }

 }  // End

上面的代码可以编译!

static public int writeToitemTable(String itemnameIn, String itemcodeIn, String descriptionIn,
                                        float unitpriceIn, float stockIn, String styleIn, String finishIn)
    {
          // Variable to hold the SQL query
          String SQLString;

          // Build a string containing the SQL INSERT instruction to be used later
          SQLString = "INSERT INTO item VALUES ('" + itemcodeIn + "','" + itemnameIn + "','" + descriptionIn + "','" + unitpriceIn + "','" 
                                            + stockIn + "','" + styleIn + "','" + finishIn + "')";


           try
              {
                    // The createStatement() method creates a Statement object.  Object will be
                    // attached to my reference variable (statement) defined at the top of class.
                    statement = connectionTofireplaceDB.createStatement();

                    // The executeUpdate() statement can be used here to execute an 
                    // SQL INSERT instruction.
                    statement.executeUpdate (SQLString);

              }
            catch (SQLException exception)
              {
                   return (-1);     // Return -1 if problem writing record to file

              }

            return (0);   // Return with 0 if record successfully written 

      } // End

  static public int writeTosupplierTable(String suppliernameIn, String suppliercodeIn, String addressIn)
    {
          // Variable to hold the SQL query
          String SQLString;

          // Build a string containing the SQL INSERT instruction to be used later
          SQLString = "INSERT INTO supplier VALUES ('" + suppliernameIn + "','" + suppliercodeIn + "','" + addressIn + "')";


           try
              {
                    // The createStatement() method creates a Statement object.  Object will be
                    // attached to my reference variable (statement) defined at the top of class.
                    statement = connectionTofireplaceDB.createStatement();

                    // The executeUpdate() statement can be used here to execute an 
                    // SQL INSERT instruction.
                    statement.executeUpdate (SQLString);

              }
            catch (SQLException exception)
              {
                   return (-1);     // Return -1 if problem writing record to file

              }

            return (0);   // Return with 0 if record successfully written 

      } // End          

当我在表单中输入详细信息并点击提交按钮时,我得到一个返回值 -1,这导致显示一个消息框,指出写入数据库时​​出现问题。为什么?

更新

这些是我可以获得的错误消息:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at ItemEntryScreen.writeItemRecord(ItemEntryScreen.java:392)
    at ItemEntryScreen.actionPerformed(ItemEntryScreen.java:348)
    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:6038)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
    at java.awt.Component.processEvent(Component.java:5803)
    at java.awt.Container.processEvent(Container.java:2058)
    at java.awt.Component.dispatchEventImpl(Component.java:4410)
    at java.awt.Container.dispatchEventImpl(Container.java:2116)
    at java.awt.Component.dispatchEvent(Component.java:4240)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
    at java.awt.Container.dispatchEventImpl(Container.java:2102)
    at java.awt.Window.dispatchEventImpl(Window.java:2429)
    at java.awt.Component.dispatchEvent(Component.java:4240)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)

最佳答案

首先,打印堆栈跟踪以查找错误。

其次,我看到人们因为“声明”而遇到这些麻烦。在值即将更改的地方使用“PreparedStatement”。如果您执行第二个建议,很可能您的问题将得到解决

第三,使用 finally() block 或其他东西关闭连接

关于java - 写入数据库表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10640028/

相关文章:

java - 如何在jboss中部署资源适配器

sql - 透视表值函数

python - 在 django 中管理 redis 连接的正确方法

MySQL:从多个表连接时出现重复值

sql - 为什么 Docker 找不到我要导入的 sql 文件?

database - Postgresql:存储函数中的 dblink

java - 如何设置在 mxGraph 的 pdf/图像导出功能中使用的自定义字体以支持 UTF-8 编码的亚洲语言文本?

java - 经过一定时间后,使线程最终进入

java - java语言中的凯撒密码密文失败

php - 选择一个表中的所有数据并将其插入到另一个表中