背景:我正在重写我的ASP.NET应用程序--目前它使用的是MySQL数据库,但我也需要支持MySQL(两者同时!)。
大多数工作都已经完成--我使用MySQL连接器/.NET处理C#的MySQL数据库(Visual 2010) --但是我在某些SQL查询上遇到了麻烦。这是我需要执行的SQL查询:
"SELECT @username=username FROM t_Users WHERE id=@id"这是我的代码:
public static int ExecuteSqlNonQuery(string i_szQuery)
{
bool bConnectionWasOpen = false;
AbstractConnection dbConnection = CMSSQLInstanceCreator.CreateConnection();
if(dbConnection.IsMySQL())
{
MySqlConnection aSqlConnection = dbConnection.GetMysConnection();
try
{
if (aSqlConnection.State == System.Data.ConnectionState.Closed)
aSqlConnection.Open();
else
if (aSqlConnection.State == System.Data.ConnectionState.Open)
bConnectionWasOpen = true;
else
throw new ApplicationException("Connection not available!");
List<MySqlParameter> aParameters1 = new List<MySqlParameter>();
aParameters1.Add(new MySqlParameter("@username", MySqlDbType.VarString, 128));
aParameters1.Add(new MySqlParameter("@id", MySqlDbType.Int32));
aParameters1[0].Direction = System.Data.ParameterDirection.Output;
aParameters1[1].Direction = System.Data.ParameterDirection.Input;
aParameters1[1].Value = (int)1;
MySqlCommand aSqlCommand = new MySqlCommand(i_szQuery, aSqlConnection);
aSqlCommand.CommandType = System.Data.CommandType.Text;
aSqlCommand.CommandTimeout = 0;
aSqlCommand.Parameters.Clear();
aSqlCommand.Parameters.AddRange(aParameters1.ToArray());
int iResult = aSqlCommand.ExecuteNonQuery();
if(iResult <= 0)
Debug.WriteLine("aResult <= 0: " + i_szQuery);
return iResult;
}
catch (Exception ex)
{
throw new ApplicationException("Cannot execute query!\nReason: '" + ex.Message + "'", ex);
}
finally
{
if (!bConnectionWasOpen && aSqlConnection.State == System.Data.ConnectionState.Open)
aSqlConnection.Close();
}
}
else
{
//... almost the same for MS SQL
}
}问题是输出参数@username (System.Data.ParameterDirection.Output;)没有填充查询的值。
如果我使用其他查询-例如。
UPDATE t_Users SET password=@new_password WHERE (password=@old_password AND id=@user)百事大吉。
我不能返回标量,因为还有许多其他查询,如
SELECT @username=username, @is_blocked=is_blocked, @full_name=full_name, @must_change_pwd=must_change_pwd ...返回许多值,我不想重写大部分代码。
看起来只有在MySQL中才会出现问题,因为相同的代码可以很好地处理MySQL。
我应该使用什么来强制MySqlParameter从查询中加载值?
发布于 2013-04-17 12:21:04
您应该能够像这样读取输出的值
aSqlCommand.Parameters["@username"].Value发布于 2015-10-11 13:03:07
显然,它是MySql .Net连接器中的一个bug,参见#75267。使用连接器v6.9.7和MySql服务器5.5.45对其进行了测试。它仍然是坏的,而2014年12月的bug报告仍然是开放的。输出参数适用于具有命令类型StoredProcedure的存储过程,而不适用于将输出参数赋值为select;命令类型文本的SELECT语句。
https://stackoverflow.com/questions/16059222
复制相似问题