<分区>
<分区>
我正在使用 MVC3 ASP,并且已将 web.config 文件配置为以 root 身份登录 MYSQL 数据库。我创建了许多可以很好连接的存储过程。我现在想将此登录用户更改为公共(public)用户,称为 tempuser,而不再是 root。
但是,当我将登录用户从“root”更改为“tempuser”时,出现错误: 无法将“System.DBNull”类型的对象转换为“System.String”类型
我在执行 ExecuteNonQuery() 时收到上述错误。
我已通过以下方式授予对这些功能的访问权限: 将函数 check_user_exists 上的执行授予 tempuser@'%';
我还在此表上授予了“选择”和“更新”权限,我正在访问该函数使用的表。我可以以 tempuser 身份登录 mysql 命令行并手动调用该函数,没有任何问题。但是当我运行 ExecuteNonQuery() 时,我收到上述错误。我目前正在使用 Visual Web Developer 2010、Razor Engine、MVC3。
请帮忙。
我已经尝试了好几个星期了,但没有成功。
这是正在执行的代码。 ExecuteScalar() 函数是错误所在。该错误是这个问题的主题:但是,如果我以“root”用户身份登录,则不会收到错误。
[HttpPost]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
DBController dbcontroller = new DBController();
if (dbcontroller.DBConnection())
{
MySqlCommand command = new MySqlCommand("check_user_exists_signup", dbcontroller.conn);
command.CommandType = System.Data.CommandType.StoredProcedure;
// Add parameters for the check_user_exists_signup STORED FUNCTION
command.Parameters.Add(new MySqlParameter("@userName", model.UserName));
command.Parameters["@userName"].Direction = System.Data.ParameterDirection.Input;
// RETURN parameter for the insert_users STORED FUNCTION
MySqlParameter cnt_user = command.Parameters.Add("@cnt_user", MySqlDbType.Int32);
command.Parameters["@cnt_user"].Direction = System.Data.ParameterDirection.ReturnValue;
try
{
command.ExecuteScalar();
object ret = command.Parameters["@cnt_user"].Value;
dbcontroller.conn.Close();
存储过程是:
CREATE DEFINER=`root`@`localhost` FUNCTION `check_user_exists_signup`(
userName varchar(20)) RETURNS int(11)
DETERMINISTIC
BEGIN
DECLARE cnt_user int;
select count(*) into cnt_user
from users
where user_name = userName;
RETURN cnt_user;
END
最佳答案
Unable to cast object of type 'System.DBNull' to type 'System.String'
嗯,你不能这样做。你必须说
string s = null;
object value = reader["columnName"];
if(value != System.DBNull) {
s = (string)value;
}
或者类似的东西。关键是,您不能将 System.DbNull
转换为字符串。因此,如果您当前正在处理的行中的列 columnName
的值为 null
,那么您必须检测它。否则,可以安全地继续进行转换(假设基础数据类型是string
)。
I have been trying for weeks now with no luck.
最重要的是,您不应该花费数周来解决这样的问题。我将消息“无法将类型为‘System.DBNull’的对象转换为类型为‘System.String’”进入 Google 并弹出 this answer这基本上是你的问题,和我给你的解决方案相同,只是编码有点不同。
关于.net - 无法将类型 'System.DBNull' 的对象强制转换为类型 'System.String',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10141092/