简体   繁体   English

如何转换查询结果?

[英]How to transform query results?

I need transform string query to int to be evaluated.我需要将字符串查询转换为 int 进行评估。 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.您可以执行类似的操作来读取cmd.ExecuteReader()命令的结果。

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 :如果您只对(单个)记录的存在感兴趣,您可以查询countExecuteScalar

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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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