Background: I am rewriting my ASP.NET application - currently it uses MS SQL database but I need to support also MySQL (both in the same time!).
Most of work is done - I used MySQL Connector/Net for work with MySQL database from C# (Visual Studio 2010) - but I have troubles with certain SQL queries. This is SQL query I need to execute:
"SELECT @username=username FROM t_Users WHERE id=@id"
Here is my code:
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
}
}
The problem is that the Output parameter @username (System.Data.ParameterDirection.Output;) is not filled with the value from query.
If I use other query - e.g.
UPDATE t_Users SET password=@new_password WHERE (password=@old_password AND id=@user)
Everything is fine.
I cannot return scalar as there are many other queries like
SELECT @username=username, @is_blocked=is_blocked, @full_name=full_name, @must_change_pwd=must_change_pwd ...
returning many values and I do not want to rewrite most of code.
It looks like there is problem only in MySQL because the same code works with MS SQL fine.
What should I use to force MySqlParameter to load the value from query?