mysql - JBDC和MYSQL空值插入表

标签 mysql jdbc exception

下面是简单的登录系统。目前,它允许我在表中输入空白的用户名和密码,即使每个索引都指定为 NOT NULL?它不允许我输入重复项,这正是我想要的,但是如何捕获输入的空白​​参数?我错过了什么?

注册Servlet

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

LoginService方法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();

    }

最佳答案

要解决当前问题,您可以将其添加到 addNewUser 方法的开头(行之前: ps = connection.prepareStatement("...");)

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

您应该在 JDBC 参数中传递真正的 NULL 值(空字符串不够好)

关于mysql - JBDC和MYSQL空值插入表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16795854/

相关文章:

mysql - 如何删除元组作为工资低于平均水平?

linux 和文本编辑器中的 java.lang.ClassNotFoundException : com. mysql.jdbc.Driver 异常

在 netbeans 中运行的 java web 应用程序 - SQLException : No suitable driver

php - PHP 上传和 MySQL 插入后的白色空图像

php - 如何将 doc 和 pdf 文件从 android 应用程序保存到 mysql 数据库中?

kotlin - 使用 NamedParameterJdbcTemplate 为每个查询设置不同的查询超时

shell - ArangoDB 异常

exception - Azure数据工厂复制事件错误记录异常处理

c# - 如何记录异常信息以进行故障排除?

mysql - 如何使用键盘快捷键或菜单项注释 MySQL Workbench 中的代码?