How to get SQL result saved into a C# variable?

前端 未结 3 1298
日久生厌
日久生厌 2021-02-05 18:12

I have troubles finding out how to save an SQL result into a String or whatever type the result returns.

My SQL query is:

SELECT SUM(Length) FROM tbl_tes         


        
3条回答
  •  悲&欢浪女
    2021-02-05 18:43

    You can use SqlDataReader . Here is a sample :

    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnectionString"].ToString());
    
    
    SqlCommand read_command = new SqlCommand("SELECT SUM(Length) FROM tbl_test WHERE TITLE LIKE '@t%'", con);
            read_command.Parameters.Add("@t", SqlDbType.NVarChar).Value = Str;
            SqlDataReader read_rd;
            string SUM ;
            try
            {
                con.Open();
                read_rd = read_command.ExecuteReader();
                if (read_pass_rd.HasRows)
                {
                    while (read_rd.Read())
                    {
                        SUM = read_rd.GetString(0);
                    }
                }
                read_rd.Close();
                con.Close();
            }
            catch (Exception)
            {
                if (con.State == ConnectionState.Open)
                    con.Close();
            }
    

    and the 'Str' is a string is the string that you search for, and 'SUM' string is the answer.

提交回复
热议问题