2016-11-30 1 views
0

Ich verwende einen Video-Kurs zur Datenbank-Programmierung mit der aktuellen Lektion mit Java, um eine Verbindung zu MySQL herzustellen. Ich habe das Video verfolgt und sogar die Textarbeitsdatei für dieses spezielle Problem kopiert (so weiß ich, dass der Code funktioniert), aber ich bekomme immer noch einen Fehler. Die Datenbank soll Informationen für Bücher speichern: isbn, Titel, Autor, Herausgeber und Preis. Ich habe die exakt gleichen Daten über die Befehlszeile eingefügt, aber wenn ich das Programm für eine GUI verwende, bekomme ich einen "Daten abgeschnitten" -Fehler. Ich weiß, es gibt mehrere Antworten in "Daten abgeschnitten" Fehler; Ich sehe jedoch nicht, wo die Daten zu groß sind, besonders beim Einfügen von Arbeiten mit einer nicht-GUI-Schnittstelle. Alle Datentypen sind VARCHAR außer dem Preis, der FLOAT ist. Der Fehler, den ich bekommen ist:Daten abgeschnitten für Spalte bei Verwendung von FLOAT in GUI

Einsatz in Buchwerte ('978.007.106.789', 'Stuck On Java', 'J Reid', '9.99', 'Osborne') Fehler beim Ausführen von SQL java.sql.SQLException: Daten abgeschnitten für Spalte 'Preis' in Zeile 1

GUI Code ist:

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

den Code ein, um einfach die Befehlszeile ist:

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

die einzige diffe Ich habe festgestellt, dass der Preis im GUI-Code in Anführungszeichen steht. Das Entfernen der Anführungszeichen verursacht jedoch den gleichen Fehler ohne Anführungszeichen. Auch habe ich bemerkt, dass der GUI-Code den Preis auf 8 Bit setzt (ursprünglicher Code war 10), während Float in MySQL nicht auf irgendwas gesetzt ist (ich glaube, ich lese auf einem anderen Post, dass es standardmäßig 8 Bit ist) verwendet 8). Ich wandte mich an den Autor des Videos und schlug vor, dass ich die Preisnotierungen entfernen sollte. Aber wie ich gesagt habe, hat das nicht geholfen ... auch dieser Code wurde von seiner Arbeitsdatei kopiert, die an dem Video arbeitete. Jede Hilfe wird geschätzt.

Datenbank-Code ist:

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

Können Sie bitte auch den Code, den Sie verwenden, um die Tabelle erstellen? – npinti

+0

drop table book; Band ( \t isbn_13 varchar (13) Primärschlüssel, \t Titel varchar (50), \t Autor varchar (50), \t Verlag varchar (50), \t Preis Schwimmer (11) ) schaffen; –

+0

Wenn Sie die Textfelder initialisieren, verwenden Sie den parameterlosen Konstruktor. Wenn Sie von der GUI lesen, verwenden Sie 'isbn.getText()' '' isbn.getText(). Trim() '. Dies sollte unnötige Leerräume entfernen. – npinti

Antwort

0

starten wieder von Grund auf ich völlig das Buch Tisch fiel dann neu erstellt es über den MySQL-Code verwenden. Nachdem ich die Tabelle neu erstellt hatte, konnte ich mit dem GUI-Code einfügen. Ich bin mir nicht sicher, was die Ursache meines Problems war, aber das Fallenlassen und Nachstellen des Tisches schien es zu beheben.

Verwandte Themen