gpt4 book ai didi

MySQL 系统.FormatException : Input string was not in a correct format

转载 作者:行者123 更新时间:2023-11-29 00:56:28 25 4
gpt4 key购买 nike

目前,我正在使用 ASP.NET MVC3 和 MySQL 创建一个应用程序,当我尝试从数据库中检索用户的名字时,我收到一个 System.FormatException:输入字符串的格式不正确。

这是我的代码:

public string GetUserFirstName(UInt64 id)
{
DBConnections databaseCnnString = new DBConnections();
string connectionString = "server=123.123.com;user=me;database=db1;port=3306;password=abcdef";
MySqlConnection cnn = new MySqlConnection(connectionString);

try
{
cnn.Open();
string sp_GetFName = "SP_GET_FNAME";
MySqlCommand cmd = new MySqlCommand(sp_GetFName, cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("id", id);
cmd.Parameters["id"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("first_name", MySqlDbType.VarChar);
cmd.Parameters["first_name"].Direction = ParameterDirection.Output;

object result = cmd.ExecuteScalar();
if (result != null)
{
string fname = Convert.ToString(result);
return fname;
}
else
{
string fname = "friend";
return fname;
}

}
catch (Exception ex)
{
throw (ex);
}
finally
{
cnn.Close();
cnn.Dispose();
}
}

这是 MySQL 存储过程:

CREATE DEFINER=`0001`@`%` PROCEDURE `SP_GET_FNAME`(IN id BIGINT(20), OUT first_name VARCHAR(60))
BEGIN
DECLARE user_id BIGINT(20) DEFAULT id;
DECLARE output VARCHAR(60);
SELECT `FName` FROM `users` WHERE USERID=user_id INTO output;
SET first_name = output;
END

问题似乎是在执行 cmd.ExecuteScalar() 时。

我的问题是什么?

提前致谢!

最佳答案

我的复制和粘贴错误。按预期工作的正确代码是:

public string GetUserFirstName(UInt64 id)
{
DBConnections databaseCnnString = new DBConnections();
string connectionString = "server=123.123.com;user=me;database=db1;port=3306;password=abcdef";
MySqlConnection cnn = new MySqlConnection(connectionString);

try
{
cnn.Open();
string sp_GetFName = "SP_GET_FNAME";
MySqlCommand cmd = new MySqlCommand(sp_GetFName, cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("id", id);
cmd.Parameters["id"].Direction = ParameterDirection.Input;
cmd.Parameters.Add(new MySqlParameter("first_name", MySqlDbType.VarChar));
cmd.Parameters["first_name"].Direction = ParameterDirection.Output;
cmd.ExecuteScalar();
string fname = Convert.ToString((cmd.Parameters["first_name"].Value));

return fname;

}
catch (Exception ex)
{
throw (ex);
}
finally
{
cnn.Close();
cnn.Dispose();
}
}

更正:cmd.Parameters.Add(new MySqlParameter("first_name", MySqlDbType.VarChar));不是:cmd.Parameters.AddWithValue("first_name", MySqlDbType.VarChar);

在我的例子中,用户表中的 FNAME 字段不能为 NULL;因此,无需检查代码中返回的 NULL 值。

关于MySQL 系统.FormatException : Input string was not in a correct format,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5887038/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com