簡體   English   中英

如何將T-SQL SELECT轉換為C#變量

[英]How to T-SQL SELECT into C# variables

我正在使用SQL Server 2008 R2和C#ASP.NET 4

我有一個名為myTable的簡化表,其中包括以下列:Col1,Col2,Col3,Col4

CREATE TABLE [dbo].[myTable](
    [Col1] [int] NULL,
    [Col2] [int] NULL,
    [Col3] [nvarchar](50) NULL,
    [Col4] [int] NULL
) ON [PRIMARY]
GO
INSERT [dbo].[myTable] ([Col1], [Col2], [Col3], [Col4]) VALUES (0, 0, N'@', 0)
INSERT [dbo].[myTable] ([Col1], [Col2], [Col3], [Col4]) VALUES (1, 2, N'c', 4)
INSERT [dbo].[myTable] ([Col1], [Col2], [Col3], [Col4]) VALUES (11, 22, N'cc', 44)

(原始表要寬得多)

如何SELECT兩列(或20或200)列到C#變量或變量數組/變量列表中,或其他比以下方法更有效或更好的方法:

object obj = new object();
string sql = "SELECT Col2, Col3 FROM myTable WHERE Col1=0";
using (SqlConnection conn = new SqlConnection(mySqlCalss.DatabaseConnectionString() ))
            {
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Connection.Open();
                obj = cmd.ExecuteNonQuery();
            }

在某種程度上,我可以使用類似:

int myVar1 = (int)ojb[0];
string myVar2 = (string)obj[1];

然后:

lblMyASPlable1.Text = myVar1.ToString();
lblMyASPlable2.Text = myVar2;

您使用的是“ ExecuteNonQuery”,它執行了上面所說的操作,並沒有像查詢(即選擇)那樣執行。 嘗試ExecuteReader。

SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
    Console.WriteLine(String.Format("{0}", reader[0]));
}

使用讀入DataReader 查看Datareader的運行情況

您需要SQLDataAdapter

DataTable table = new DataTable();
string sql = "SELECT Col2, Col3 FROM myTable WHERE Col1=0";
using (SqlConnection conn = new SqlConnection(mySqlCalss.DatabaseConnectionString() ))
{
   SqlCommand cmd = new SqlCommand(sql, conn);
   cmd.Connection.Open();
   SqlDataAdapter adapter = new SqlDataAdapter(cmd);
   adapter.Fill(table);                
}

int myVar1;
string myVar2;
if(table.Rows.Count>0)
{
  myVar1 = (int)table.Rows[0]["Col2"];
  myVar2 = (string)table.Rows[0]["Col3"];
} 

您可能想研究像dapper這樣的MicroORM

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM