本问题已经有最佳答案,请猛点这里访问。
我正在使用MVC3 ASP,并已将我的web.config文件配置为以root用户身份登录MYSQL数据库。我创建了许多存储过程,我可以很好地连接。我现在想要将此登录用户更改为公共用户,称为tempuser而不是root。
但是,当我将登录用户从"root"更改为"tempuser"时,我收到错误:
无法将"System.DBNull"类型的对象强制转换为"System.String"类型
我在执行ExecuteNonQuery()时遇到上述错误。
我通过以下方式授予了访问权限的权限:
GRANT EXECUTE ON FUNCTION check_user_exists to tempuser @'%';
我还在这个表上授予了'select'和'update',我可以访问该函数使用的内容。我可以作为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'"进入谷歌并向上弹出这个答案,这基本上是你的问题,和我给你的相同解决方案,只是编码了一点不同。
失败发生在ExecuteScalar点。 因此,一旦执行了存储过程,它就会失败并且不会按照上面的代码通过这一点。 那么,我在哪个时候添加你的代码? 因为在调用executeScalar之前,我设置了参数。
在.Net中,如果数据为NULL,则表示为System.DBNull.Value,它是在DB中表示NULL的特定类型,您无法将其隐式转换为任何内容,因此,假设您有一个对象包含来自DB的值命名为theValue,但数据为NULL然后theValue实际上是一种System.DBNull,那么下面的表达式将抛出异常:
if(theValue =="blabla")
{
....
}
要防止这很容易,要么检查类型,要么在其上做一个ToString(只要你确定它不是.net null)你会得到一个空字符串
你的第二个建议是不一致的。 它将以一个空字符串结束。 Console.WriteLine("" == System.DBNull.Value.ToString());空字符串与Null不同
我只是建议如何避免这种异常,是的它不一样,但在我的代码中体验它对我来说足够了