2012-05-17 2 views
3

공급자이라는 두 개의 데이터베이스 테이블에 새 레코드를 쓰려고합니다.DB 테이블에 쓰기

데이터베이스 연결과 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) 
+0

D. 당신이 원하는 쿼리 결과를 얻기 시작하면 .. 그 여기 .... 내가 그것을 원활하게 실행 희망으로 구현 더 R &에 대한 당신의 마음의 콘텐츠에 수정하려고 당신은'SQLException'의 필드를보고 오류가 무엇인지 보았는가? – dsolimano

+3

'catch (SQLException 예외) {return (-1); }'> 예외 처리 전략을 수행해야합니다! 그렇게한다면 버그를 쉽게 발견 할 수 있습니다! – home

+1

SQL 쿼리 작성을위한 문자열 연결? 불행히도 제어 할 수 없게 전파되는 것은 매우 나쁜 생각입니다 ... – thkala

답변

2

첫째, 오류를 찾기 위해 스택 트레이스를 인쇄 :

업데이트

이 내가 점점 수있는 오류 메시지입니다.

두 번째로, 나는 "Statement"때문에 사람들이 이러한 문제를 겪고있는 것을 보았다. 값은 당신이

세 번째 두 번째 제안을한다면 아마 당신의 문제가 해결 될 것입니다 change.Most하려고 장소에서 "PreparedStatement의"를 사용, 마지막에() 블록 또는 뭔가

1

봐를 사용하여 연결을 닫습니다 내 코드 아래, 그리고

import java.sql.Connection; 

import java.sql.DriverManager; 

import java.sql.PreparedStatement; 

import java.sql.ResultSet; 

import java.sql.ResultSetMetaData; 

import java.sql.SQLException; 

import java.sql.Statement; 

import java.util.Vector; 

import javax.swing.JTable; 

import com.my.views.*; 


public class DBDiary { 

    Connection conn; 
    EntryDisplay entryD; 


    public DBDiary(){ 

     this.getConn(); 

    } 

    public Connection getConn(){ 

     try { 
      conn = getConnection(); 

     } catch (SQLException e) { 

      System.out.println("Connection Couldnt be Obtained"); 
     } 
      return conn; 
    } 


    public static Connection getConnection() throws SQLException { 

     String drivers = "com.mysql.jdbc.Driver"; 
     String url = "jdbc:mysql://localhost:3306/test"; 
     String username = "root"; 
     String password = "root"; 

     System.setProperty(drivers,""); 

     return DriverManager.getConnection(url,username,password); 

    } 

    public void createTable() { 

     Statement stat = null; 
     String sql = "create table items(item varchar(30), cost DOUBLE(12,3),day integer,month varchar(15), year integer);"; 
     if (conn != null){ 

      try { 

       stat = conn.createStatement(); 

      } catch (SQLException e) { 

       System.out.println("Connection Couldnt be Obtained"); 
      } 

      if (stat != null){ 

       try { 
        stat.executeUpdate(sql); 
       } catch (SQLException e) { 
        //System.out.println("Table already Exists"); 
       }  
      } 

     } 
    } 


    public void addItems(String item, double cost,int day, String month, int year) { 

     PreparedStatement pstat = null; 

     String sql = "INSERT INTO ITEMS Values(?,?,?,?,?);"; 

     if (conn != null){ 

      try { 

       pstat = conn.prepareStatement(sql); 


      } catch (SQLException e) { 

       System.out.println("Connection Couldnt be Obtained"); 
      } 

     } 

     if (pstat != null) { 

      try { 

       pstat.setString(1, item); 
       pstat.setDouble(2, cost); 
       pstat.setInt(3, day); 
       pstat.setString(4, month); 
       pstat.setInt(5,year); 
       pstat.executeUpdate(); 

      } catch (SQLException e) { 

       e.printStackTrace(); 
       System.out.println("Insertion of the entry was unsuccessful"); 
      } 
     } 


    } 


    public static void main(String[] args) { 

    DBDiary db = new DBDiary(); 
    db.createTable(); 
    db.addItems("Cards", 40.00,29, "Mar", 2012); 


    } 
+0

매우 유용한 게시물, 감사합니다. 하지만 여전히이 문제를 해결할 수없는 것 같습니다. 그러나 다시 시도해 주셔서 감사합니다. – silverj2k7

+0

나는 사용하여 연결을 종료하고 있습니다 : 정적 공공 INT의 closeConnection()를 { // 코드 여기에 가까운에 대한} 그러나 당신이 다시 엽니 다 다음에 대한 데이터베이스 연결을 종료하고 I가 삽입 운동을 할 때 언급하는 각 삽입? – silverj2k7

+0

나는 그렇게 해왔다. – silverj2k7

관련 문제