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

前端 未结 3 1299
日久生厌
日久生厌 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.

提交回复
热议问题