2016-11-30 4 views
0

데이터베이스 프로그래밍에 비디오 과정을 사용하고 있으며 현재 강의는 Java를 사용하여 MySQL에 연결합니다. 나는 비디오를 따라 갔고이 특정 문제에 대한 텍스트 작업 파일을 복사하기도 했으므로 (코드 작동을 알았으므로) 여전히 오류가 발생합니다. 데이터베이스는 도서 정보 (isbn, 제목, 저자, 발행자 및 가격)를 저장합니다. 명령 줄을 사용하여 똑같은 데이터를 삽입했지만 GUI 용 프로그램을 사용할 때 "데이터 잘림"오류가 발생합니다. "데이터 잘림"오류에 여러 답이 있다는 것을 알고 있습니다. 그러나 특히 데이터를 삽입 할 때 비 GUI 인터페이스를 사용하여 데이터가 너무 큰 부분을 볼 수 없습니다. FLOAT 인 가격을 제외한 모든 데이터 유형은 VARCHAR입니다. 내가 오류는 다음과 같습니다 데이터 : 책 값 ('978007106789', '자바에 붙어', 'J 리드', '9.99', '오스본') 오류 실행 SQL 은 java.sql.SQLException에GUI에서 FLOAT를 사용할 때 데이터에 대해 잘린 데이터

삽입 행에서 열 '가격'에 대한 잘릴 1

GUI 코드는 다음과 같습니다

package Connection; 

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 
import java.sql.*; 
import java.util.*; 

public class InsertRecord extends JFrame { 
    private JButton getBookButton, insertBookButton; 
    private JList bookList; 
    private Connection connection; 
    private JTextField isbn, title, author, price, publisher; 
    private JTextArea errorText; 

    public InsertRecord() { 
     try { 
     Class.forName("com.mysql.jdbc.Driver").newInstance(); 
     } 
     catch (Exception e) { 
     System.err.println("Unable to load driver."); 
     System.exit(1); 
     } 
    } 

    public void loadBook() { 
     Vector<String> v = new Vector<String>(); 
     try { 
     Statement statement = connection.createStatement(); 
     ResultSet rs = statement.executeQuery("select title from book"); 
     while (rs.next()) { 
      v.addElement(rs.getString("title")); 
     } 
     rs.close(); 
     } 
     catch (SQLException e) { 
     System.err.println("Error executing SQL"); 
     } 
     bookList.setListData(v); 
    } 

    private void createGUI() { 
     Container c = getContentPane(); 
     c.setLayout(new FlowLayout()); 
     bookList = new JList(); 
     loadBook(); 
     bookList.setVisibleRowCount(2); 
     JScrollPane bookListScrollPane = new JScrollPane(bookList); 

     getBookButton = new JButton("Get Book Title"); 
     getBookButton.addActionListener(
     new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       String query = "select * from book where title = " + 
         bookList.getSelectedValue(); 
       try { 
        Statement statement = connection.createStatement(); 

        ResultSet rs = statement.executeQuery(
        "select * from book where title = '" 
        + bookList.getSelectedValue() + "'"); 
      /*ResultSet rs = statement.executeQuery(
        "select * from book where title = 'Java:How To Program'"); */ 
        if (rs.next()) { 
        isbn.setText(rs.getString("isbn")); 
        title.setText(rs.getString("title")); 
        author.setText(rs.getString("author")); 
        price.setText(rs.getString("price")); 
        publisher.setText(rs.getString("publisher")); 
        } 
       } 
       catch (SQLException ex) { isbn.setText(query); } 
      } 
     } 
    ); 

     insertBookButton = new JButton("Insert Book"); 
     insertBookButton.addActionListener (
     new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       try { 
        Statement statement = connection.createStatement(); 
        String insert = "insert into book values("; 
        insert += "'" + isbn.getText() + "',"; 
        insert += "'" + title.getText() + "',"; 
        insert += "'" + author.getText() + "',"; 
        insert += "'" + price.getText() + "',"; 
        insert += "'" + publisher.getText() + "')"; 
        System.out.println(insert); 
        /*int i = statement.executeUpdate("insert into book values(" + 
        "'" + isbn.getText() + "'," + 
        "'" + title.getText() + "'," + 
        "'" + author.getText() + "'," + 
        "'" + price.getText() + "'," + 
        "'" + publisher.getText() + ")");*/ 
        int i = statement.executeUpdate(insert); 
        errorText.append("Inserted " + i + " rows succcessfully."); 
        bookList.removeAll(); 
        loadBook(); 
       } 
       catch (SQLException ex) { 
        System.err.println("Error executing SQL"); 
        ex.printStackTrace(); 
       } 
      } 
      } 
    ); 

     JPanel first = new JPanel(new GridLayout(3,1)); 
     first.add(bookListScrollPane); 
     first.add(getBookButton); 
     first.add(insertBookButton); 

     isbn = new JTextField(13); 
     title = new JTextField(50); 
     author = new JTextField(50); 
     price = new JTextField(8); 
     publisher = new JTextField(50); 
     errorText = new JTextArea(5,15); 
     errorText.setEditable(false); 

     JPanel second = new JPanel(); 
     second.setLayout(new GridLayout(6,1)); 
     second.add(isbn); 
     second.add(title); 
     second.add(author); 
     second.add(price); 
     second.add(publisher); 

     JPanel third = new JPanel(); 
     third.add(new JScrollPane(errorText)); 

     c.add(first); 
     c.add(second); 
     c.add(third); 
     setSize(800, 400); 
     setVisible(true); 
    } 

    public void connectToDB() throws Exception { 
    //Connection conn = null; 
     try { 
     String userName = "jesse"; 
     String password = "password"; 
     String url = "jdbc:mysql://localhost/library"; 
     Class.forName("com.mysql.jdbc.Driver").newInstance(); 
     connection = DriverManager.getConnection(url, userName, password); 
     //if (conn != null) System.out.println("Database connection successful."); 
     } 
     catch (SQLException e) { 
     System.out.println("Can't connect to database"); 
     System.exit(1); 
     } 
    } 

    private void init() throws Exception{ 
     connectToDB(); 
    } 

    public static void main(String[] args) throws Exception { 
     InsertRecord insert = new InsertRecord(); 

     insert.addWindowListener(
     new WindowAdapter() { 
      public void windowClosing(WindowEvent e) { 
       System.exit(0); 
      } 
     } 
    ); 

     insert.init(); 
     insert.createGUI(); 
    } 
} 

단순히 명령 행을 사용하는 삽입 코드는 다음과 같습니다

package Connection; 

import java.sql.*; 
import java.io.*; 

public class InsertDB { 

    Connection connection; 

    public InsertDB(){ 

     try { 
      Class.forName("com.mysql.jdbc.Driver").newInstance(); 
     } 
     catch (Exception e) { 
      System.out.println("Could not load driver."); 
      e.printStackTrace(); 
     } 
    } 


    public void ConnectToDB() { 
     try { 
      connection = DriverManager.getConnection("jdbc:mysql://localhost/library", "jesse", "password"); 
      System.out.println("Connected to database."); 
     } 
     catch (Exception e) { 
      System.out.println("Cannot connect to database."); 
      e.printStackTrace(); 
     } 
    } 

    public void execSQL() { 
     try { 
      Statement stmt = connection.createStatement(); 
      BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); 
      System.out.print("Enter the isbn: "); 
      String isbn = input.readLine(); 
      System.out.print("Enter the title: "); 
      String title = input.readLine(); 
      System.out.print("Enter the author: "); 
      String author = input.readLine(); 
      System.out.print("Enter the publisher: "); 
      String pub = input.readLine(); 
      System.out.print("Enter the price: "); 
      String p = input.readLine(); 
      double price = Double.parseDouble(p); 


      String insert = "Insert into book values (" + "'" + isbn + "','" + title + "','" + author + "','" + pub + "'," + price + ")"; 
      System.out.println(insert); 
      int inserted = stmt.executeUpdate(insert); //returns 1 for success, 0 for failure 
      if (inserted > 0) { 
       System.out.println("Successfully inserted " + inserted + " row."); 
      } 
     } 
     catch (Exception e) { 
      System.out.println("Error executing SQL"); 
      e.printStackTrace(); 
     } 
    } 
    public static void main(String[] args){ 
     InsertDB conn = new InsertDB(); 
     conn.ConnectToDB(); 
     conn.execSQL(); 
    } 
} 

유일한 diffe 나는 GUI 코드에서 가격이 따옴표로 묶여 있다는 것을 알아 차렸다. 그러나 따옴표를 제거하면 따옴표없이 동일한 오류가 발생합니다. 또한 GUI 코드는 8 비트 (원래 코드는 10) 였지만, float은 MySQL에서 설정되지 않은 것으로 나타났습니다 (다른 포스트에서 읽으면 기본적으로 8 비트가됩니다 ...) 사용 8). 나는 비디오의 저자에게 손을 뻗쳤다. 그는 가격을 둘러싼 인용문을 삭제할 것을 제안했다. 그러나 내가 말했듯이 이것은 도움이되지 않았습니다 ... 또한이 코드는 비디오 작업을했던 작업 파일에서 복사되었습니다. 어떤 도움을 주셔서 감사합니다.

데이터베이스 코드입니다 : 나는 완전히 그 책 테이블을 떨어 위의 MySQL의 코드를 사용하여 다시

drop table book; 

create table book (
    isbn_13 varchar(13) primary key, 
    title varchar(50), 
    author varchar(50), 
    publisher varchar(50), 
    price float(11) 
); 
+0

테이블 생성 기능을 사용하는 코드도 포함시킬 수 있습니까? – npinti

+0

드롭 테이블 북; 테이블 책 생성 ( \t isbn_13의 VARCHAR (13)가 기본 키 \t 표제 VARCHAR (50) \t 저자 VARCHAR (50) \t 게시자 VARCHAR (50), \t 가격 플로트 (11) ); –

+0

텍스트 필드를 초기화 할 때 매개 변수없는 생성자를 사용하십시오. GUI에서 읽을 때'isbn.getText()'대신'isbn.getText(). trim()'을 사용하십시오. 이렇게하면 불필요한 공백이 제거됩니다. – npinti

답변

0

처음부터 다시 시작. 테이블을 다시 만든 후에 GUI 코드를 사용하여 삽입 할 수있었습니다. 내 문제의 원인이 무엇인지 모르겠지만 테이블을 떨어 뜨리고 다시 만들면 문제가 해결 된 것 같습니다.