简体   繁体   English

如何将SQL结果保存到C#变量中?

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

I have troubles finding out how to save an SQL result into a String or whatever type the result returns. 我很难找到如何将SQL结果保存到String或结果返回的任何类型。

My SQL query is: 我的SQL查询是:

SELECT SUM(Length) FROM tbl_test WHERE TITLE LIKE 't%'

Here I need a function that sums up the length of all data-rows where title begins with the letter "T", when executing the query in MS-SQL it returns "188.99" (the SQL type is decimal) 这里我需要一个函数来总结所有数据行的长度,其中title以字母“T”开头,当在MS-SQL中执行查询时,它返回“188.99”(SQL类型为十进制)

My question is, how do I get to save that value into a C# variable? 我的问题是,如何将该值保存到C#变量中? The query always returns ONE row with the particular value, which I want to save into a variable. 查询始终返回具有特定值的一行,我想将其保存到变量中。 I have a C# function to execute the query, I just need the value from that row, 188.99, to be saved into a variable. 我有一个C#函数来执行查询,我只需要将该行的值188.99保存到变量中。 Any suggestions are cool, no matter if I the result is saved into a decimal variable or string. 无论我将结果保存为十进制变量还是字符串,任何建议都很酷。

Try calling .ExecuteScalar() on the SqlCommand that you prepare for it. 尝试在准备它的SqlCommand上调用.ExecuteScalar()。 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. 您可以根据需要打开和关闭SqlConnections(每次执行操作时打开和关闭SoP,或者使用相同方法打开和关闭一系列操作),因为.Net不会真正关闭真实的连接,它会“软关闭“它并将实时连接重新连接回连接池以便以后再循环。

You can use SqlDataReader . 您可以使用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. 'Str'是一个字符串,是你搜索的字符串,'SUM'字符串就是答案。

You need to connect C# to your Database through some of the available methods: 您需要通过一些可用的方法将C#连接到您的数据库:

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

I would think ADO.NET is the most basic and straightforward way to do it given you actual query. 考虑到实际查询,我认为ADO.NET是最基本,最简单的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM