如何获得SQL结果保存到C#的变量? [英] How to get SQL result saved into a C# variable?

查看:119
本文介绍了如何获得SQL结果保存到C#的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有麻烦找出如何在SQL结果保存到一个字符串或任何类型的结果回报。

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

我的SQL查询是

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

在这里我需要总结的地方有字母T称号beginns,在MS-SQL执行查询时,返回188.99(SQL类型的所有数据行的长度的功能是十进制)

here I need a function that sums up the length of all datarows where title beginns with the letter "T", when executing the query in MS-SQL it returns "188.99" (the sql type is decimal)

我的问题是,我怎么得到这个值保存到C#的变量?查询总是返回一行与特定的价值,这是我想保存到一个变量。我有一个C#函数来执行查询,我只需要值该行,188.99,保存到一个变量。任何的建议是冷静,不管我的结果保存到小数变量或字符串。

my question is, how do I get to save that value into a C# variable? 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. any suggestions are cool,no matter if I the result is saved into a decimal variable or string.

推荐答案

尝试调用.ExecuteScalar( )您为它准备的SqlCommand。 EG:

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();

您可以打开和关闭SqlConnections只要你喜欢(它的SoP的打开和关闭,每次尽可能多的你做一次手术,或同一方法系列OPS的),因为净不会真正关闭真正的连接,它就会软关闭它和放下的实时连接放回回收后,一个连接池。

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.

这篇关于如何获得SQL结果保存到C#的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆