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

标签 java mysql user-interface floating-point truncated

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

插入账面值(value)('978007106789','Stuck On Java','J Reid','9.99','Osborne') 执行 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();
    }
}

我注意到的唯一区别是 GUI 代码中的引号中的价格;但是,删除引号只会导致没有引号的相同错误。我还注意到 GUI 代码将价格设置为 8 位(原始代码为 10),而 MySQL 中的 float 没有设置为任何内容(我相信我在另一篇文章中读到默认情况下是 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)
);

最佳答案

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

关于java - 在 GUI 中使用 FLOAT 时列的数据被截断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40890434/

相关文章:

java - 在 JSP 中/使用 JSP 实现 ActiveMQ 消息监听器

java - react 器WebFlux : help to understand how to work flatMap()

javascript - Laravel 将本地主机 MySql 数据库同步到托管服务器

mysql - 在 MySQL 查询中将行转换为列

html - 如何在输入框周围创建 CSS 边框?

java - 使用 Java 和 JMX/MBean 访问 Weblogic JMS

java - jdatechooser作为mysql查询中的参数

mysql - 如何将用户数据与其他表连接起来?

Java Swing GUI 控件停止,而操作在后端执行

JavaFX 不在 BorderPane 上打印网格