我正在使用 MySQL 及其最后一个可用的 JDBC 驱动程序,在 User
表上,其所有字段均有 NOT NULL
约束,即 id
、姓名
、密码
和电子邮件
。
在我的 Java EE 应用程序中,我首先以这种方式调用了一个简单的 Statement
:
statement = connection.createStatement();
statement.executeUpdate( "INSERT INTO User (name, password, email) "
+ "VALUES ('" + paramName + "', '" + paramPassword + "', '" + paramEmail + "');" );
其中paramName
、paramPassword
和paramEmail
都是字符串。我将空字符串传递给此请求,并且在表中成功插入了一个包含空值的新行,因为 MySQL 认为空字符串不同于空条目。
然后,我使用了 PreparedStatement
来代替:
preparedStatement = connection.prepareStatement( "INSERT INTO User (name, password, email) VALUES(?, ?, ?);" );
preparedStatement.setString( 1, paramName );
preparedStatement.setString( 2, paramPassword );
preparedStatement.setString( 3, paramEmail );
preparedStatement.executeUpdate();
但是这一次,当我向请求传递空字符串时,出现以下错误:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'name' cannot be null
所以这是我的问题:PreparedStatement
或其setString()
方法是否将空字符串转换为空值?我查了一下,但没有在 javadoc 中找到有关此行为的任何信息。
最佳答案
java.sql.PreparedStatement 的文档在 setString 方法中没有说明任何相关内容。我查看了 MySQL ConnectorJ 的源代码,但我也没有找到任何东西。您确定您的字符串不为空吗?
关于mysql - PreparedStatement 是否将空字符串转换为 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11497622/