2015-11-05 37 views
0

我有一個包含問題和答案我的webapp仍然插入「」和空值如何解決這個問題?

 CREATE TABLE question(
     id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, 
     ttype INT NOT NULL, 
     content VARCHAR(1000) NOT NULL, 
     a1 VARCHAR(200) NOT NULL, 
     a2 VARCHAR(200) NOT NULL, 
     a3 VARCHAR(200) NOT NULL, 
     a4 VARCHAR(200) NOT NULL, 
     a5 VARCHAR(200) NOT NULL, 
     correctAnswer VARCHAR(10) 
     ) 

和我使用(MVC JSP的servlet)在數據庫中插入

我addquestion()在DAO類是

public int Addquestion(Question q){ 
int type = q.getTtype(); 
String content = q.getContent(); 
String a1 = q.getA1(); 
String a2 = q.getA2(); 
String a3 = q.getA3(); 
String a4 = q.getA4(); 
String a5 = q.getA5(); 
String correctAnswer =q.getCorrectAnswer(); 

Connection con = null; 
PreparedStatement insertQuestion = null; 
int result = 0; 
try{ 
    con = DBConnection.createConnection(); 
    insertQuestion = con.prepareStatement("insert into question(ttype,content,a1,a2,a3,a4,a5,correctAnswer) VALUES (?,?,?,?,?,?,?,?)"); 
    insertQuestion.setInt(1,type); 
    insertQuestion.setString(2,content); 
    insertQuestion.setString(3, a1); 
    insertQuestion.setString(4, a2); 
    insertQuestion.setString(5, a3); 
    insertQuestion.setString(6, a4); 
    insertQuestion.setString(7, a5); 
    insertQuestion.setString(8, correctAnswer); 

    result = insertQuestion.executeUpdate(); 


} 
catch(SQLException e){ 
    e.printStackTrace(); 
} 


    return result; 
    } 
MySQL表

問題是我認爲(NOT NULL)足以在(Web App)提交空表單時返回錯誤(result = 0)。但我的數據庫仍然採用空值(或「」)?

(注:我不知道什麼是HTML形式的空當回報我提交null或「」)

非常感謝你

回答

1

是的,它肯定會在數據庫中添加null or ""值。爲什麼,因爲準備的語句將創建SQL這樣的事情(如果你想看到最後的查詢,把System.out.println(insertQuestion);executeUpdate()之前)

insert into question(ttype,content,a1,a2,a3,a4,a5,correctAnswer) VALUES (1,'test','test','test','test','test','test','test') 

現在讓我們假設你已經把HTML表單上沒有價值了一段not null領域比查詢將成爲

(1,'test','test','test','test','','','test') 

empty String ("")不等於null即使你在HTML表單把null雖然它會把它作爲

(1,'test','test','test','test','null','null','test') 

它會插入數據庫(無錯誤)。

因此,最好是把驗證在客戶端(JavaScript,jQuery的)不空字段,而不是驗證它在服務器上。

希望這會有所幫助:)