在java中采用空值的插入操作
我有一个名为tutorial的mysql数据库,其中包含一个表“devices”,我有一个swing程序,它通过文本框向表中插入一行。插入一行很好,但是当我将文本框留空并单击“确定”按钮时,一个空列被添加到该行中。如何避免添加空行。以及即使单个文本框为空也避免添加行。我已经在mysql.plz帮助中定义了NOTNULL约束 这是我的密码:在java中采用空值的插入操作,java,mysql,swing,Java,Mysql,Swing,我有一个名为tutorial的mysql数据库,其中包含一个表“devices”,我有一个swing程序,它通过文本框向表中插入一行。插入一行很好,但是当我将文本框留空并单击“确定”按钮时,一个空列被添加到该行中。如何避免添加空行。以及即使单个文本框为空也避免添加行。我已经在mysql.plz帮助中定义了NOTNULL约束 这是我的密码: jb.addActionListener(new ActionListener(){ public void actionPerformed( A
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();
}
}
});
基本上,您需要检查文本字段的长度是否为
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
}
在按钮的ActionListener中,您需要检查文本字段的值,以确保它包含值。如果没有,则显示带有错误消息的JOptionPane,并将焦点设置回文本字段。