从同一列存储多个值作为变量. SQL到C# [英] Storing more than one value from the same column as a varible. Sql to C#

查看:75
本文介绍了从同一列存储多个值作为变量. SQL到C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我目前正在尝试从数据库中同一列但在不同行中读取多个值.

下面是代码

Hi, I am currently trying to read in multiple values from the same column in a data base but at diffrent rows.

Below is code

string AlphaX = null, AlphaY = null, BetaX = null, BetaY = null;

               SqlCommand userCommand = userConnection.CreateCommand();

               userCommand.CommandText = "SELECT X, Y FROM [dbo].[Coordinates] WHERE GroupName=''Alpha''";

               SqlDataReader reader = userCommand.ExecuteReader();

               while (reader.Read())
               {
                   AlphaX = reader["X"].ToString();
                   AlphaY = reader["Y"].ToString();

                   MessageBox.Show(AlphaX);
                   MessageBox.Show(AlphaY);
               }



我希望接下来可以存储GroupName"Beta"的X和Y值.存储值后是否必须关闭此连接并执行另一个连接?还是缺少某些内容?.



I want to be able to store the X and Y values of GroupName ''Beta'' next. Do I have to close this connection after having stored the value and do another one or am I missing something?.

推荐答案

不,您可以在相同的连接.
No, you can do a second SqlCommand on the same connection.




为什么不执行诸如SELECT X, Y, GroupName FROM [dbo].Coordinates]之类的常规查询,此后,请根据GroupName拆分查询:

Hi,

Why you do not execute a general Query like SELECT X, Y, GroupName FROM [dbo].Coordinates], after that, split the query according the GroupName:

while (reader.Read())
{
    string currentGroupName = reader["GroupName"].ToString();
    
    switch (currentGroupName)
    {
        case "Alpha":
            AlphaX = reader["X"].ToString();
            AlphaY = reader["Y"].ToString();
            break;
        case "Beta":
            BetaX = reader["X"].ToString();
            BetaY = reader["Y"].ToString();
            break;
    }
}



在这种情况下,您只执行一个查询,并且比两次查询数据库更快地关闭连接.

希望这会有所帮助.

致以最诚挚的问候,祝您有愉快的一天,
停止



In this case you only execute one query and you could close the connection faster than querying the DB twice.

Hope this helps.

Best regards and have a nice day,
Stops


这篇关于从同一列存储多个值作为变量. SQL到C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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