从SQL Server检索并存储两个值到c#中

本文关键字:两个 Server SQL 检索 存储 | 更新日期: 2023-09-27 18:11:12

这就是我想要实现的。我想从同一张表的同一行获取两个值并将它们存储到两个变量中。我在MVC中做这个。

下面是我正在做的:

SqlCommand amd = new SqlCommand("SELECT [Value1] FROM [ExampleTable] where Ad_name=@adname", con);
SqlCommand bmd = new SqlCommand("SELECT [Value2] FROM [ExampleTable] where Ad_name=@adname", con);
amd.Parameters.AddWithValue("@adname", aname);
bmd.Parameters.AddWithValue("@adname", aname);
imgpath1 = amd.ExecuteScalar().ToString();
imgpath2 = bmd.ExecuteScalar().ToString();

但这是我想要的:

SqlCommand amd = new SqlCommand("SELECT [Value1] AND [Value2] FROM [ExampleTable] where Ad_name=@adname", con);
amd.Parameters.AddWithValue("@adname", aname);
imgpath1 = Value1;
imgpath2 = Value2;

我如何在不写多个查询的情况下实现这一点?由于

从SQL Server检索并存储两个值到c#中

查看SqlCommand ExecuteReader返回SqlDataReader的方法:

using(var command = new SqlCommand("SELECT [Value1], [Value2] FROM [ExampleTable] where Ad_name=@adname", con))
{
    command.Parameters.AddWithValue("@adname", aname);
    using(var reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
            imgpath1 = reader[0];
            imgpath2 = reader[1];
        }
    }
}

你的第二个SQL命令不会工作,如果你想要的值,你不能做一个标量查询…

试题:

 SqlCommand command = new SqlCommand("SELECT [Value1], [Value2] FROM [ExampleTable] where Ad_name=@adname", con);

并添加参数

那么你可以

var reader = command.ExecuteReader();

并通过

获取值
reader["[Value1]"];
reader["[Value2]"];

本质上,执行标量查询意味着只返回单个值的查询。

使用逗号作为检索列之间的分隔符,使用GetOrdinal来避免像[1]和[2]这样的常量。

const string ColumnOne = "ColumnOne";
const string ColumnTwo = "ColumnTwo";
var sqlCmd = new SqlCommand("select [VALUE1] as " + ColumnOne + ", [VALUE2] as " + ColumnTwo + " from table", sqlConn);
var sqlCmdReader = sqlCmd.ExecuteReader();
if (sqlCmdReader.Read())
    {
    var resultOne= sqlCmdReader.GetString(sqlCmdReader.GetOrdinal(ColumnOne));
    var resultTwo= sqlCmdReader.GetString(sqlCmdReader.GetOrdinal(ColumnTwo ));
}

使用ExecuteReader方法只调用一次数据库。
请注意,所需的单列是如何在SELECT之后列出的,用逗号分隔。
这是SELECT语句
所需的常见基本语法此方法返回一个DataReader,您可以使用它来获取一行的单个值。
我假设您的查询只返回一条记录,因此,循环不是严格必要的。

SqlCommand amd = new SqlCommand("SELECT [Value1], [Value2] FROM [ExampleTable] where Ad_name=@adname", con);
amd.Parameters.AddWithValue("@adname", aname);
SqlDataReader reader = amd.ExecuteReader();
while(reader.Read())
{
    imgPath1 = reader[0].ToString();
    imgPath2 = reader[1].ToString();
}