C#sql查询if()else()基于结果null?

5 c#

标题可能令人困惑,但基本上我想做一些与此相关的事情,

string sql = "select dataset1 from dbo.ste where project = 'whatever' and date = '11/30/10'";
        SqlConnection con = new SqlConnection("Data Source= Watchmen ;Initial Catalog= doeLegalTrending;Integrated Security= SSPI");
        con.Open();
        SqlCommand cmd = new SqlCommand(sql, con);
        cmd.ExecuteNonQuery();
        con.Close();

if(cmd "is not null")
{
//do this string
}
else
{

//do this one
}
Run Code Online (Sandbox Code Playgroud)

显然cmd"不是空")不是真的,但我想你们可能会明白这一点.

bit*_*ise 7

我不明白为什么当问题中的查询是SELECT语句时,每个人都试图使用ExecuteNonQuery或ExecuteScalar.如果是存储过程调用,它根据值的存在来处理INSERT与UPDATE的逻辑,则ExecuteScalar会有意义,因为您可以从存储过程返回所需的任何单个值.

但是,考虑到问题的结构,我倾向于这个作为答案.

// Automatically dispose  the connection when done
using(SqlConnection connection = new SqlConnection(sqlConnection.ConnectionString)) {
    try {
        connection.Open();

        // query to check whether value exists
        string sql =  @"SELECT dataset1 
                        FROM   dbo.ste 
                        WHERE  project = 'whatever'
                               AND date = '2010-11-30'";

        // create the command object
        using(SqlCommand command = new SqlCommand(sql, connection)) {
            using(SqlDataReader reader = command.ExecuteReader()) {
                // if the result set is not NULL
                if(reader.HasRows) {
                    // update the existing value + the value from the text file
                }
                else {
                    // insert a value from a text file
                }
            }
        }
    }
    finally {
        // always close connection when done
        if(connection.State != ConnectionState.Closed) {
            connection.Close();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

WHERE EXISTS如果您不想回传完整匹配,可以更改要使用的查询,但是根据它的声音,您最多只能有1个匹配.


Alb*_*nbo 2

看来你要先做var result = cmd.ExecuteScalar();然后比较if (result == DBNull.Value)