我在 Java JDBC 代码中的 try 语句有问题

问题描述 投票:0回答:1

我正在开发餐厅管理系统。我使用 Sqlite studio 创建了数据库,并且正在使用 JDBC 将 Jframe 设计与数据库连接起来。 但是当我运行代码时出现问题,我认为问题出在try语句上。 这是我的代码:

private void SaveeditPriceActionPerformed(java.awt.event.ActionEvent evt) {                                              
    // TODO add your handling code here:
    try{
        String sql = "UPDATE menu SET price=? WHERE itemID=? ;";
        pst= con.prepareStatement(sql);
         pst.setString(1, price.getText());
        pst.setString(2, itemIDprice.getText());
        pst.executeUpdate();
        JOptionPane.showMessageDialog(null, "Price Updated");
        
      java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new menu().setVisible(true);
        }
    }); 
    }
    catch(Exception e)
            {
           e.printStackTrace();
           JOptionPane.showMessageDialog(null, "Update Failed!");
    }

    
}                        

我期待消息“价格已更新”,并且更新后的价格会在我的数据库中自动编辑。 我询问了chatgpt,但没有得到任何有用的解决方案。

java jdbc sqlitestudio
1个回答
0
投票

将数据库代码移至用户界面之外的其他位置。让代码在没有用户界面的情况下运行。

使用 try-with-resources 语法自动关闭您的

PreparedStatement
对象和
Connection
对象。

像这样未经测试的代码。

public class RepositorySQLite
{
    // Member fields
    private final DataSource dataSource;

    // Constructors
    public RepositoryH2 ( final DataSource dataSource )
    {
        this.dataSource = Objects.requireNonNull( dataSource );
    }

    // Database access methods

    @Override
    public boolean changePriceOnMenuItem ( final int price , final int menuItemId )
    {
        @Language ( "SQL" )
        String sql = """
                UPDATE menu_ 
                SET price_ = ? 
                WHERE id_ = ?
                ;
                """;
        try (
                Connection connection = this.dataSource.getConnection( ) ;
                PreparedStatement preparedStatement = connection.prepareStatement( sql ) ;
        )
        {
            preparedStatement.setString( 1 , price );
            preparedStatement.setString( 2 , menuItemId );

            int countRows = preparedStatement.executeUpdate( );
            if ( countRows == 0 ) { throw new IllegalStateException( "No menu item with ID # " + id ) } 
            else if ( countRows == 1 ) { return true ; } // The happy path.
            else if ( countRowes > 1 ) { throw new IllegalStateException( "Multiple menu items with ID # " + id + " were updated with new price." ) ; }
            else { throw new IllegalStateException( "A negative number of menu item rows matched id of " + id + " which should not be possible." ) ; }
        } catch ( SQLException e )
        {
            throw new RuntimeException( e );
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.