1
我有一個名爲教程的mysql數據庫,其中包含一個表「devices」,我有一個swing程序,它通過文本框向表中插入一行。它可以很好地插入行,但是當我將文本框留空並單擊「確定」按鈕時,將在row.how中添加一個空列,以避免添加空行並避免添加行,即使單個文本框爲空。我已經在mysql.plz幫助中定義了非null約束。插入操作在Java Swings中取空值
這裏是我的代碼:
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並將焦點重新放在文本字段上。 – camickr