【问题标题】:replace comboBox value into number when inserted into sql插入sql时将comboBox值替换为数字
【发布时间】:2015-07-26 18:53:52
【问题描述】:

我知道如何将组合框值插入到 sql 中,但不知道如何将组合框值替换为 sql 中的数字。

这是我的组合框编码和处理按钮的一部分。

User.java

 JComboBox comboBox_1 = new JComboBox();
           comboBox_1.setBounds(126, 105, 140, 20);
           contentPane.add(comboBox_1);
           comboBox_1.addItem("RM100-RM200");
           comboBox_1.addItem("RM200-RM300");
           comboBox_1.addItem("RM300-RM400");

JButton btnNewButton = new JButton("Process");
        btnNewButton.setBounds(360, 296, 89, 23);
        contentPane.add(btnNewButton);
        btnNewButton.addActionListener(new ActionListener(){
  public void actionPerformed(ActionEvent e){
        String a=(String)comboBox.getSelectedItem().toString();
         Case ca= new Case();
      try {
                    ca.addPlace(a);
                    LoginGUI um= new LoginGUI();
                    um.setVisible(true);

                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
        }
        });

Case.java

        public void addPlace( String r) throws Exception{

        DatabaseConnection db=new DatabaseConnection();
        Connection connect=db.getConnection();
        String sql="Insert into menu(Budget)VALUES (?)";

        PreparedStatement ps=connect.prepareStatement(sql);
        ps.setString(1,r);

        ps.executeUpdate();

        connect.close();
        ps.close();

    }

假设用户选择 RM100-RM200,值“1”将插入到 sql 中,而不是 RM100-RM200。有人可以帮忙吗?

【问题讨论】:

    标签: java mysql sql-server combobox


    【解决方案1】:

    【讨论】:

    • 我可以自己改号码吗?
    • 是的,使用 setSelectedItem 或 setSelectedIndex
    【解决方案2】:

    你测试过你的代码吗? 在您编写的 actionPerformed() 中,

    String a = (String) comboBox.getSelectedItem().toString();

    对象组合框没有在代码中初始化。 您的意思是 comboBox_1 因为它是您在代码中实际初始化的唯一 JcomboBox 对象。

    还有

    (String) comboBox.getSelectedItem().toString();

    实际上不需要对 String 的类型转换,因为 toString 只返回一个 String。

    【讨论】:

    • 对不起我的错..它应该是 String a=(String)comboBox_1.getSelectedItem().toString();
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 2021-03-11
    • 2022-08-15
    • 1970-01-01
    • 2023-03-24
    相关资源
    最近更新 更多