我已经编写了这个查询以获得一些结果,如果我想将结果保存在数组中我必须做什么?我想在IF语句中使用col1和col2中的值,这就是我想将它们保存在数组中的原因.
var con = new SqlConnection("Data Source=local;Initial Catalog=Test;Integrated Security=True");
using (con)
using (var command = new SqlCommand("SELECT col1,col2 FROM some table", con))
{
con.Open();
command.ExecuteNonQuery();
}
Run Code Online (Sandbox Code Playgroud)
Tim*_*ter 32
通常我会使用一个类:
public class ClassName
{
public string Col1 { get; set; }
public int Col2 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
现在你可以使用循环来填充列表,ToArray如果你真的需要一个数组:
ClassName[] allRecords = null;
string sql = @"SELECT col1,col2
FROM some table";
using (var command = new SqlCommand(sql, con))
{
con.Open();
using (var reader = command.ExecuteReader())
{
var list = new List<ClassName>();
while (reader.Read())
list.Add(new ClassName { Col1 = reader.GetString(0), Col2 = reader.GetInt32(1) });
allRecords = list.ToArray();
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,我假设第一列是a string,第二列是a integer.只是为了证明C#是类型安全的以及如何使用这些DataReader.GetXY方法.
Hab*_*bib 16
而不是任何Array你可以加载你的数据,DataTable如:
using System.Data;
DataTable dt = new DataTable();
using (var con = new SqlConnection("Data Source=local;Initial Catalog=Test;Integrated Security=True"))
{
using (var command = new SqlCommand("SELECT col1,col2" +
{
con.Open();
using (SqlDataReader dr = command.ExecuteReader())
{
dt.Load(dr);
}
}
}
Run Code Online (Sandbox Code Playgroud)
您也可以使用SqlDataAdapater填充DataTable
SqlDataAdapter da = new SqlDataAdapter(command);
da.Fill(dt);
Run Code Online (Sandbox Code Playgroud)
稍后您可以迭代每一行并比较如下:
foreach (DataRow dr in dt.Rows)
{
if (dr.Field<string>("col1") == "yourvalue") //your condition
{
}
}
Run Code Online (Sandbox Code Playgroud)
使用 SQL 数据读取器:
在这个例子中,我使用一个列表而不是一个数组。
try
{
SqlCommand comm = new SqlCommand("SELECT CategoryID, CategoryName FROM Categories;",connection);
connection.Open();
SqlDataReader reader = comm.ExecuteReader();
List<string> str = new List<string>();
int i=0;
while (reader.Read())
{
str.Add( reader.GetValue(i).ToString() );
i++;
}
reader.Close();
}
catch (Exception)
{
throw;
}
finally
{
connection.Close();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
121626 次 |
| 最近记录: |