2013-05-28 39 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参数(空字符串不够好)