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

前端 未结 3 1296
日久生厌
日久生厌 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:38

    Try calling .ExecuteScalar() on the SqlCommand that you prepare for it. EG:

    SqlConnection connection = new SqlConnection(myConnectionString);
    SqlCommand cmd = connection.CreateCommand();
    cmd.CommandText = "SELECT SUM(Length) FROM tbl_test WHERE TITLE LIKE 't%'";
    
    int result = ((int)cmd.ExecuteScalar());
    connection.Close();
    

    You can open and close SqlConnections as much as you like (it's SoP to open and close each time you do an operation, or series of ops in the same method) because .Net will not really close the connection for real, it'll "soft close" it and plop the live connection back into a Connection Pool for recycling later.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-05 18:48

    You need to connect C# to your Database through some of the available methods:

    1. LinQ to SQL
    2. ADO.NET
    3. LinQ to Entities

    I would think ADO.NET is the most basic and straightforward way to do it given you actual query.

    0 讨论(0)
提交回复
热议问题