質問

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

役に立ちましたか?

解決

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();

他のヒント

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.

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top