2013-05-28 70 views
0

下面是簡單的登錄系統。目前,它將允許我輸入一個空白的用戶名和密碼,即使每個索引被指定爲NOT NULL,也可以放入表中。它不會允許我輸入我想要的重複項,但是如何從輸入中捕獲空白參數?我錯過了什麼?JBDC和MYSQL空值插入表

註冊的Servlet

.... 
LoginService loginService = new LoginService(); 
      connection = loginService.getConnection(connection); 
      loginService.addNewUser(preparedStatement, connection, newUserId, newUserPassword, newUserFirstName, newUserLastName); 
... 

login服務的方法AddNewUser函數

public void addNewUser(PreparedStatement ps, Connection connection, String newUserId, String newUserPassword,String newUserFirstName,String newUserLastname) throws SQLException 
    { 
     ps = connection.prepareStatement("INSERT INTO users (userId ,password , userFirstName, userLastName)VALUES(?,?,?,?)"); 
     ps.setString(1, newUserId); 
     ps.setString(2, newUserPassword); 
     ps.setString(3, newUserFirstName); 
     ps.setString(4, newUserLastname); 

     ps.executeUpdate(); 

    } 
+0

它是空白還是實際爲NULL? –

+0

對不起,它是空白的,這是不是被認爲是同一件事? – Calgar99

+0

不是,有些數據庫認爲空白等價於NULL(例如Oracle),但SQL標準和大多數數據庫認爲空白不同於任何其他值(包括空格)。另請參閱http://dev.mysql.com/doc/refman/5.0/en/working-with-null.html –

回答

2

爲了解決當前的問題,你可以將它添加到AddNewUser函數法(前行的開頭:PS =連接。 prepareStatement(「...」);)

if (newUserId != null && "".equals(newUserId.trim())) 
    newUserId = null; 
if (newUserPassword != null && "".equals(newUserPassword.trim())) 
    newUserPassword = null; 

您應該在th中傳遞實際的NULL值e JDBC參數(空字符串不夠好)