2

An SQL aggregate function counting number of name enteries in DB.

string cnnStr = ConfigurationManager.ConnectionStrings["LGFConnectionString"].ConnectionString;
string mySQL = "SELECT COUNT(*) FROM  " + which.table + " WHERE " + which.column + " = ?pram;";
string value = null;

using (MySqlConnection cnn = new MySqlConnection(cnnStr))
{
        using (MySqlCommand cmd = new MySqlCommand(mySQL, cnn))
        {
            MySqlParameter param = new MySqlParameter("?pram", MySqlDbType.VarChar, 128);
            param.Value = which.text;
            cmd.Parameters.Add(param);

            cnn.Open();

            value = cmd.ExecuteScalar() as string;
            value = cmd.ExecuteScalar().ToString();

            cnn.Close();
        }
}

Notice that I have called cmd.ExecuteScalar twice. Interesting part is that the query returns different results.

value = cmd.ExecuteScalar() as string;

doesn't return the correct value. It returns null for both if name is present or missing in the name column.

value = cmd.ExecuteScalar().ToString();

returns correctly. This returns "1" if present and "0" if missing.

In searching the web, I haven't found an understandable explanation.

I have read that if name is missing from name column, then cmd.ExecuteScalar will return null.

What is the difference between:

value = cmd.ExecuteScalar() as string;
value = cmd.ExecuteScalar().ToString();

Thank you, deDogs

1

3 Answers 3

3

as in docs

The as operator is used to perform conversions between compatible types.

The as operator is like a cast except that it yields null on conversion failure instead of raising an exception

// if cmd.ExecuteScalar() is string then return string
// if not then return null
// this will return null, because cmd.ExecuteScalar() won't return string
// for your code it should return Int32
value = cmd.ExecuteScalar() as string;

ToString() in docs

ToString is the major formatting method in the .NET Framework. It converts an object to its string representation so that it is suitable for display. (For information about formatting support in the .NET Framework, see Formatting Types.)

// return a string that represents the current object
// will return correct value because it casts Int32 value to string value
value = cmd.ExecuteScalar().ToString();
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, yes I had read this and understand, but when executed, cmd.ScalarExecute() as string returns null for if name is present or missing. Where cmd.ScalarExecute().ToString(); returns correct results.
I have added additional comments. Simply ExecuteScalar returns int. First option (as) will return null because int is not string, second option will return correct value because you are calling int.ToString() method, which converts int value to string value.
Thank you, I missed the idea of compatible types. So, I tried: int? value = (int?)cmd.ExecuteScalar(); I would think this would work, but it throws an invalid cast?
Take a look at this, you may as well try casting it to long?
0

The 'as' keyword will return null if the objects type does not match what you are attempting to cast it to.

What is happening in your case is that the returned object is an int and when you call toString on this, it will give you a string representation of the integer. When you use as against it, it gives you a null.

3 Comments

boldWhen you use as against it, it gives you a null. bold Using the as operator on a integer returns null?
In this case, yes. Effectively, as is similar to casting, except you will get a null instead of an exception being thrown. Since you have an int and are using 'as String', you will get a null back.
Thank you, something I didn't realize. I just learned something very important. Thank you -- All...
0

You are doing two different things above. Let's change your code to the following:

decimal value = cmd.ExecuteScalar();
string str1 = value as string;
string str2 = value.ToString();

str1 will be null because decimal cannot be cast to a string. str2 will be the value because you can call ToString() on a decimal.

4 Comments

Using your code, there are two lines with error: decimal value = cmd.ExecuteScalar(); compile error: cann't convert object to decimal. string str1 = value as string; compile error: cann't convert decimal to string.
That's possible - I did not try to compile it. I just wrote it to illustrate why you see the different results.
What if the Execute scalar return null or DBNull ? Standard decimal is not nullable type ...
As he/she was getting a numeric return value based on the question it was not returning null. In my answer I was trying to illustrate the difference between as and ToString(), not address all the other possibilities.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.