【问题标题】:Insert operation taking null values in java swings在 java swing 中插入取空值的操作
【发布时间】:2013-11-25 04:58:40
【问题描述】:

我有一个名为 tutorial 的 mysql 数据库,其中包含一个表“设备”,我有一个 swing 程序,它通过文本框向表中插入一行。它可以很好地插入一行,但是当我将文本框留空并单击“确定”按钮时,会在行中添加一个空列。如何避免添加空行。即使单个文本框为空,也要避免添加行.我已经在 mysql.plz 帮助中定义了 not null 约束。

这是我的代码:

jb.addActionListener(new ActionListener(){

     public void actionPerformed( ActionEvent e ) {
         try {
                Class.forName("com.mysql.jdbc.Driver");
                System.out.println("Driver loading success!");
                String url = "jdbc:mysql://localhost:3306/tutorial";
                String name = "root";
                String password = "ranjini123";
        try {
                java.sql.Connection con = DriverManager.getConnection(url, name, password);
                System.out.println("Connected.");
                String text1=jt1.getText();
                String text2=jt2.getText();
                String text3=jt3.getText();
                String text4=jt4.getText();
                String text5=jt5.getText();
                ps = con.prepareStatement (
                    "INSERT INTO devices (asset_id,name,project,emp_id,emp_name) VALUES(?,?,?,?,?)");
                  try{ 

                          ps.setString (1, text1);
                          ps.setString (2, text2);
                          ps.setString (3, text3);
                          ps.setString (4, text4);
                          ps.setString(5,text5);                                      
                          ps.executeUpdate(); 
                          JOptionPane.showMessageDialog(null,"new device added");


                   }
                   catch(NullPointerException n)
                   {
                       n.printStackTrace();
                   }
            }
            catch (SQLException n)
            {
                n.printStackTrace();
            }
         }
            catch(Exception n) 
            {
                n.printStackTrace();
            }   
     }

});

【问题讨论】:

  • 在按钮的 ActionListener 中,您需要检查文本字段的值以确保它包含值。如果不是,则显示带有错误消息的 JOptionPane 并将焦点重新设置在文本字段上。

标签: java mysql swing


【解决方案1】:

基本上,您需要检查任何文本字段的长度是否为null 或0。你需要在这里检查他们是否是null,否则它可能会抛出NullPointerException...

String text1=jt1.getText();
String text2=jt2.getText();
String text3=jt3.getText();
String text4=jt4.getText();
String text5=jt5.getText();

if (text1 != null && !text1.trim().isEmpty() &&
    text2 != null && !text2.trim().isEmpty() &&
    text3 != null && !text3.trim().isEmpty() &&
    text4 != null && !text4.trim().isEmpty() &&
    text5 != null && !text5.trim().isEmpty()) {
     //... Do insert
 } else {
     // Deal with the fact that one or more of the values are invalid
 }

【讨论】:

    猜你喜欢
    • 2016-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多