【发布时间】: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 并将焦点重新设置在文本字段上。