简体   繁体   中英

How to transform query results?

I need transform string query to int to be evaluated. I'm going well or exists another way to do that?

This is a extract to the code. Is it possible to transform the result, or is not?

Code:

string query = "SELECT Movie.Code FROM Movie WHERE Movie.Code = @code";

int i = 0;
i = int.Parse(query);

using (SqlCommand cmd = new SqlCommand(query))
{
    cmd.Connection = con;
    con.Open();

    using (SqlDataReader sdr = cmd.ExecuteReader())
    {
        string R1 = "OK";

        if (sdr.Read())
        {
            if (i > 0)
            {
                Re1 =  "OK";
            }
            else
            {
                 Re1 = "Fail";
            }
        }

        return Re1;
    }
}

You're trying to parse the query before it actually retrieves a result.

i = int.Parse(query);

You can do something like this to read the results of the cmd.ExecuteReader() command.

if (reader.HasRows) {
        while (reader.Read())
        {
           if (reader.GetInt32(0) > 0)
           {
              Re1 =  "OK";
           }
           else {
              Re1 = "Fail";
           }
        }
    }
    else {
        Console.WriteLine("No rows found.");
    }

If you are only interested in the existence of (a single) record(s) you can just query the count and ExecuteScalar :

string query = "SELECT COUNT(Movie.Code) FROM Movie WHERE Movie.Code = @code";

int i = 0;

using (SqlCommand cmd = new SqlCommand(query))
{
    cmd.Connection = con;
    con.Open();

    i = (Int32)cmd.ExecuteScalar();

    if(i > 0)
    {
        // OK
    }
    else
    {
        // Fail
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM