我在使用SqlCommand的帮助时候看到下面一个功能,觉得挺好,但是有一些疑问该怎么使用:
下面是从msdn粘贴过来的:典型的 ExecuteScalar 查询可以采用类似于下面的 C# 示例的格式:   复制代码 
 cmd.CommandText = "SELECT COUNT(*) FROM dbo.region";
 Int32 count = (Int32) cmd.ExecuteScalar();
---------------------------
我原来使用SqlCommand的习惯:
                
            string con_str = ******;
            SqlConnection con = new SqlConnection(con_str);
                string check_total = "select count(*) from " + table_name;                SqlCommand check_total_cmd = new SqlCommand(check_total, con);
                Int32 row_num = (Int32)check_total_cmd.ExecuteScalar();
--------------------
上面两种方式都是返回查询的数据库表的行数,看代码的长度,觉得第一种比较短,但是在使用cmd之前,该怎么初始化cmd呢?
请高手给指点一下 

解决方案 »

  1.   

    SqlConnection con = new SqlConnection(con_str); 
    SqlCommand cmd= con.CreateCommand();
      

  2.   

    using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection())
    {
    string con_str = "******"; 
    conn.ConnectionString = con_str;
    System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
    cmd.Connection = conn;
    cmd.CommandText = "SELECT COUNT(*) FROM dbo.region";
    try
    {
    conn.Open();
    Int32 count = (Int32)cmd.ExecuteScalar();
    }
    catch (Exception ex)
    {
    Console.WriteLine(ex.Message);
    }
    }