添加参数

时间:2015-03-01 09:06:06

标签: java

我想为Input对话框添加参数,以便程序不会继续它们为空。我不知道怎么做才能帮忙。

try
{
    String query="insert into student (firstname,secondname,password) values (?,?,?)";
    PreparedStatement pst=connection.prepareStatement(query);
    pst.setString(1, JOptionPane.showInputDialog("First Name"));
    pst.setString(2, JOptionPane.showInputDialog("Second Name"));
    pst.setString(3, JOptionPane.showInputDialog("Your Password"));
    pst.execute();
    pst.close();
}
catch (Exception ex)
{
    JOptionPane.showMessageDialog(null,"Something Went Wrong!");
}

1 个答案:

答案 0 :(得分:0)

只需使用值验证来包装代码,例如:

String firstname = JOptionPane.showInputDialog("First Name");
String secondname = JOptionPane.showInputDialog("Second Name");
String password = JOptionPane.showInputDialog("Your Password");

if(null == firstname || null == secondname || null == password)
{
    throw new IllegalArgumentException("Missing Parameters!");
}
else
{
    try
    {
        String query="insert into student (firstname,secondname,password) values (?,?,?)";
        PreparedStatement pst=connection.prepareStatement(query);
        pst.setString(1, firstname);
        pst.setString(2, secondname);
        pst.setString(3, password);

        pst.execute();

        pst.close();

    }
    catch (Exception ex)
    {
        JOptionPane.showMessageDialog(null,"Something Went Wrong!");
    }

}