如何在C#Asp.net中将SELECT sql查询结果保存在一个数组中
我已经编写了这个查询以获得一些结果,如果我想将结果保存在数组中我必须做什么? 我想在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(); }
通常我会使用一个类:
public class ClassName { public string Col1 { get; set; } public int Col2 { get; set; } }
现在,如果你真的需要一个数组,你可以使用循环填充列表和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(); while (reader.Read()) list.Add(new ClassName { Col1 = reader.GetString(0), Col2 = reader.GetInt32(1) }); allRecords = list.ToArray(); } }
请注意,我假设第一列是string
,第二列是integer
。 只是为了certificateC#是类型安全的以及如何使用DataReader.GetXY
方法。
您可以在DataTable
加载数据,而不是任何Array
:
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); } } }
您也可以使用SqlDataAdapater
来填充您的DataTable
SqlDataAdapter da = new SqlDataAdapter(command); da.Fill(dt);
稍后您可以迭代每一行并比较如下:
foreach (DataRow dr in dt.Rows) { if (dr.Field("col1") == "yourvalue") //your condition { } }
使用SQL DATA READER:
在这个例子中,我使用List而不是数组。
try { SqlCommand comm = new SqlCommand("SELECT CategoryID, CategoryName FROM Categories;",connection); connection.Open(); SqlDataReader reader = comm.ExecuteReader(); List str = new List (); int i=0; while (reader.Read()) { str.Add( reader.GetValue(0).ToString() ); } reader.Close(); } catch (Exception) { throw; } finally { connection.Close(); }
满容易:
public void PrintSql_Array() { int[] numbers = new int[4]; string[] names = new string[4]; string[] secondNames = new string[4]; int[] ages = new int[4]; int cont = 0; string cs = @"Server=ADMIN\SQLEXPRESS; Database=dbYourBase; User id=sa; password=youpass"; using (SqlConnection con = new SqlConnection(cs)) { using (SqlCommand cmd = new SqlCommand()) { cmd.Connection = con; cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM tbl_Datos"; con.Open(); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); foreach (DataRow row in dt.Rows) { numbers[cont] = row.Field(0); names[cont] = row.Field(1); secondNames[cont] = row.Field (2); ages[cont] = row.Field(3); cont++; } for (int i = 0; i < numbers.Length; i++) { Console.WriteLine("{0} | {1} {2} {3}", numbers[i], names[i], secondNames[i], ages[i]); } con.Close(); } } }
未提及的一个很好的替代方法是使用实体框架,它使用表的对象 – 将数据导入数组,您可以执行以下操作:
var rows = db.someTable.SqlQuery("SELECT col1,col2 FROM someTable").ToList().ToArray();
有关Entity Framework入门的信息,请参阅https://msdn.microsoft.com/en-us/library/aa937723(v=vs.113).aspx
public void ChargingArraySelect() { int loop = 0; int registros = 0; OdbcConnection conn = WebApiConfig.conn(); OdbcCommand query = conn.CreateCommand(); query.CommandText = "select dataA, DataB, dataC, DataD FROM table where dataA = 'xpto'"; try { conn.Open(); OdbcDataReader dr = query.ExecuteReader(); //take the number the registers, to use into next step registros = dr.RecordsAffected; //calls an array to be populated Global.arrayTest = new string[registros, 4]; while (dr.Read()) { if (loop < registros) { Global.arrayTest[i, 0] = Convert.ToString(dr["dataA"]); Global.arrayTest[i, 1] = Convert.ToString(dr["dataB"]); Global.arrayTest[i, 2] = Convert.ToString(dr["dataC"]); Global.arrayTest[i, 3] = Convert.ToString(dr["dataD"]); } loop++; } } } //Declaration the Globais Array in Global Classs private static string[] uso_internoArray1; public static string[] arrayTest { get { return uso_internoArray1; } set { uso_internoArray1 = value; } }
- 使用亚音速交易
- html输出中的特殊字符
- document.getElementById(’id’)。值在ASP.net javascript函数中失败
- 通过面板C#中的文本框控件进行迭代
- 什么是ASP.NET Core MVC等同于Request.RequestURI?
- 是否有任何简单的方法可以按月/年/每日单位增加DateTime,而不必像疯了一样解析它?
- 在PostBack之后将数据保存在GridView中
- Doc文件不从asp.net中的UserControl下载
- TeamCity中的MSBuild步骤考虑了app.config而不是ASP.NET WEB API项目的web.config,导致警告MSB3247