首页 > 解决方案 > 代码是否存在导致异常的问题?

问题描述

我正在开发一个简单的应用程序,可用于创建啤酒配方。该应用程序采用存储在数据库中的特定值,并使用数学公式和数量(用户输入)来计算啤酒规格。

当我运行这个“计算”按钮下的代码时,我得到了很多异常,其中主要是 java.awt 异常、javax.swing 异常和一些 SQL 异常。列出的变量是正确的,变量的拼写没有打字错误。

private void Calculate_BrewActionPerformed(java.awt.event.ActionEvent evt) {                                               
    // TODO add your handling code here:
    nameBrew = jTextField1.getText();
    Connection connFerm = null;
    Connection connHops = null;
    try {
        vols = Float.parseFloat(jTextField2.getText());
    } 
    catch (NumberFormatException e) {
        JOptionPane.showMessageDialog(null, "Enter a valid number...");
    }
    fermone = (String) jComboBox1.getSelectedItem();        
    try {
        fermmass1 = Float.parseFloat(jTextField6.getText());
    } 
    catch (NumberFormatException e) {
        JOptionPane.showMessageDialog(null, "Enter a valid number...");
    }       
    hop1 = (String) jComboBox9.getSelectedItem(); 

    try {
        hopmass1 = Float.parseFloat(jTextField10.getText());            
    }
    catch (NumberFormatException e) {
        JOptionPane.showMessageDialog(null, "Enter a valid number...");
    }
    //...............................................................................
    try {            
        connFerm = DriverManager.getConnection("jdbc:mysql://localhost:3306/fermentable_info", "root", "nerdswonka");
    } catch (SQLException ex) {
        Logger.getLogger(Create_Page.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        connHops = DriverManager.getConnection("jdbc:mysql://localhost:3306/hops_info", "root", "nerdswonka");
    } catch (SQLException ex) {
        Logger.getLogger(Create_Page.class.getName()).log(Level.SEVERE, null, ex);
    }
    //TODO add your OG calculation code here:
    String queryppg = "SELECT ppg_value INTO "+ppgval1+" FROM fermentable_info WHERE name=?";
    PreparedStatement pstFerm = null;
    ResultSet rsFerm = null; 

    try {
        pstFerm = connFerm.prepareStatement(queryppg);
        pstFerm.setString(1, jComboBox1.getSelectedItem().toString());
        rsFerm = pstFerm.executeQuery();
    } catch (SQLException ex) {
        Logger.getLogger(Create_Page.class.getName()).log(Level.SEVERE, null, ex);
    }
    ogval = (float) (((0.80*((ppgval1*(fermmass1/vols))))/1000)+1);
    jTextField9.setText(Float.toString(ogval));

    //TODO add your SRM calculation code here:
    String querylov = "SELECT lovibond INTO "+lovval+" FROM fermentable_info WHERE name=?";

    try {
        pstFerm = connFerm.prepareStatement(querylov);
        pstFerm.setString(1, jComboBox1.getSelectedItem().toString());
        rsFerm = pstFerm.executeQuery();
    }
    catch (SQLException ex) {
        Logger.getLogger(Create_Page.class.getName()).log(Level.SEVERE, null, ex);
    }
    srmval = (int) ((1.3546*lovval)-0.76);
    jTextField4.setText(Integer.toString(srmval));

    //TODO add your IBU calculation code here:
    String queryaa = "SELECT lovibond INTO "+aaval+" FROM hops_info WHERE name=?";

    try {
        pstFerm = connHops.prepareStatement(queryaa);
        pstFerm.setString(1, jComboBox9.getSelectedItem().toString());
        rsFerm = pstFerm.executeQuery();
    }
    catch (SQLException ex) {
        Logger.getLogger(Create_Page.class.getName()).log(Level.SEVERE, null, ex);
    }
    aapercent = (aaval/hopmass1);
    ibuval = (float) (0.8*((aapercent/100)*hopmass1)/vols);
    jTextField5.setText(Float.toString(ibuval));

    //TODO add your ABV calculation code here:
    abvval = (float) ((ogval-1.015)*131.25);
    jTextField3.setText(Float.toString(abvval));

    //TODO add your SQL insertion code here:
    Connection connSql = null;
    try {
        connSql = DriverManager.getConnection("jdbc:mysql://localhost:3306/saved_recipes", "root", "nerdswonka");
    } catch (SQLException ex) {
        Logger.getLogger(Create_Page.class.getName()).log(Level.SEVERE, null, ex);
    }
    String sqlIn = "INSERT INTO saved_recipes (name, og, abv, srm, ibu, volbatch)" + 
    "VALUES (?, ?, ?, ?, ?, ?)";
    try {
        pstFerm = connSql.prepareStatement(sqlIn);
        pstFerm.setString(1, nameBrew);
        pstFerm.setFloat(2, ogval);
        pstFerm.setFloat(3, abvval);
        pstFerm.setInt(4, srmval);
        pstFerm.setFloat(5, ibuval);
        pstFerm.setFloat(6, vols);
        pstFerm.executeUpdate();
    } catch (SQLException ex) {
        Logger.getLogger(Create_Page.class.getName()).log(Level.SEVERE, null, ex);
    }       
}      

我收到的任何输入的输出如下: - OG:1.0 - IBU:0.0 - SRM:0 - ABV:-1.96875 例外情况如下:

java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '0 FROM fermentable_info WHERE name='American Choco 350L'' at line 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1003)
at brewing_system.ia.Create_Page.Calculate_BrewActionPerformed(Create_Page.java:437)
at brewing_system.ia.Create_Page.access$100(Create_Page.java:17)
at brewing_system.ia.Create_Page$2.actionPerformed(Create_Page.java:280)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6525)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6290)
at java.awt.Container.processEvent(Container.java:2234)
at java.awt.Component.dispatchEventImpl(Component.java:4881)
at java.awt.Container.dispatchEventImpl(Container.java:2292)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
at java.awt.Container.dispatchEventImpl(Container.java:2278)
at java.awt.Window.dispatchEventImpl(Window.java:2750)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:751)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:702)
at java.awt.EventQueue$3.run(EventQueue.java:696)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:724)
at java.awt.EventQueue$4.run(EventQueue.java:722)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:721)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

标签: javasql

解决方案


简短回答:向数据库发送一个 SELECT,使用返回的方法ResultSet来获取值。类似于(使用虚构的列名和表名,缺少错误处理,关闭,...):

String sql = "SELECT value FROM table WHERE check = ?";

Connection conn = DriverManger.createConnection (...)
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, condition);

ResultSet rset = stmt.executeQuery();
if (rset.next()) {   // or, for multiple results: while(rset.next()) {
    String result = rset.getString("value");
    // TODO use `result`
}  // else for error mesage (not found)

显然我会使用try-with resource并捕获异常,......没有IDE或测试编写的代码,可能有错误,无法正常工作

还建议访问JDBC Basics教程!


推荐阅读