在GUI中使用FLOAT时,列的数据被截断

时间:2016-11-30 14:05:20

标签: java mysql user-interface floating-point truncated

我正在使用关于数据库编程的视频课程,当前课程使用Java连接到MySQL。我已经关注了视频,甚至为这个特定问题复制了文本工作文件(所以我知道代码有效),但我仍然收到错误。该数据库用于存储书籍信息:isbn,title,author,publisher和price。我使用命令行插入完全相同的数据,但是当我使用程序进行GUI时,我收到“数据截断”错误。我知道“数据截断”错误有多个答案;但是,我没有看到数据太大的地方,特别是在使用非GUI界面插入工作时。除价格为FLOAT外,所有数据类型均为VARCHAR。我得到的错误是:

插入书籍值('978007106789','Stuck On Java','J Reid','9.99','Osborne') 执行SQL时出错 java.sql.SQLException:第1行的“price”列截断数据

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();
    }
}

我注意到的唯一区别是价格在GUI代码的引号中;但是,删除引号只会导致相同的错误没有引号。另外我注意到GUI代码将价格设置为8位(原始代码为10),而浮点数未设置为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)
);

1 个答案:

答案 0 :(得分:0)

从头开始我完全删除了book表,然后使用上面的MySQL代码重新创建它。重新创建表后,我可以使用GUI代码插入。我不确定我的问题的原因是什么,但丢弃和重新创建表似乎解决了它。