2016-11-30 21 views
0

我正在使用數據庫編程的視頻課程,當前課程正在使用Java連接到MySQL。我跟着視頻,甚至複製了這個特定問題的文本工作文件(所以我知道代碼工作),但我仍然收到錯誤。該數據庫用於存儲書籍的信息:標題,作者,出版商和價格。我使用命令行插入了完全相同的數據,但是當我將該程序用於GUI時,出現「數據截斷」錯誤。我知道在「數據截斷」錯誤中有多個答案;但是,我沒有看到數據太大的情況,特別是在使用非GUI界面插入作品時。所有的數據類型都是VARCHAR,除了價格是FLOAT。我得到的錯誤是:在GUI中使用FLOAT時截斷列的數據

插入到賬面價值( '978007106789', '粘住的Java', 'Ĵ瑞德', '9.99', '奧斯本') 錯誤執行SQL 值java.sql.SQLException:數據在行截斷爲列 '價格' 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(); 
    } 
} 

唯一迪菲rences我注意到價格在GUI代碼中被引用;但是,刪除引號只會導致沒有引號的相同錯誤。另外我注意到GUI代碼將價格設置爲8位(原始代碼爲10),而float在MySQL中並未設置爲任何內容(我相信我在另一篇文章中讀到它默認是8位......這就是爲什麼我使用8)。我聯繫了視頻的作者,他建議我刪除有關價格的報價。但正如我所說的,這並沒有幫助...此代碼是從他的視頻工作文件複製的。任何幫助表示讚賞。

數據庫的代碼是:

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

從頭開始,我完全放棄了書表,然後使用上面的MySQL的代碼重新創建它。重新創建表後,我可以使用GUI代碼插入。我不確定我的問題的原因是什麼,但是刪除並重新創建表似乎解決了這個問題。