慕的地8271018
2023-09-27 14:44:33
我正在開發一個簡單的應用程序,可用于創建啤酒配方。該應用程序采用存儲在數據庫中的特定值,并使用數學公式和數量(用戶輸入)來計算啤酒規格。當我運行這段代碼(即“計算”按鈕下的代碼)時,我收到很多異常,其中主要是 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); }
1 回答

海綿寶寶撒
TA貢獻1809條經驗 獲得超8個贊
簡短回答:將 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 或測試編寫的代碼可能有錯誤,無法正常工作
添加回答
舉報
0/150
提交
取消