Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save SELECT sql query results in an array in C# Asp.net

Tags:

How can I save the results of an SQL query into an array?

I want to use the values (located in col1 and col2) in an IF statement, leading to my thinking of saving them in an array.

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(); } 
like image 421
Kamran Avatar asked Nov 20 '13 16:11

Kamran


People also ask

How do I store SQL query results in an array?

<? php mysql_connect("mysql153.secureserver.net","java2s","password"); mysql_select_db("java2s"); $query = "SELECT * FROM Employee"; $result = mysql_query($query); while ($row = mysql_fetch_array($result,MYSQL_NUM)) { $name = $row[1]; $developerid = $row[0]; echo "Product: $name ($developerid) <br />"; } ?>

How do you declare an array in SQL?

Define arrays as SQL variables. Use the ARRAY_AGG built-in function in a cursor declaration, to assign the rows of a single-column result table to elements of an array. Use the cursor to retrieve the array into an SQL out parameter. Use an array constructor to initialize an array.


2 Answers

Normally i use a class for this:

public class ClassName {     public string Col1 { get; set; }     public int Col2 { get; set; } } 

Now you can use a loop to fill a list and ToArray if you really need an array:

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();     } } 

Note that i've presumed that the first column is a string and the second an integer. Just to demonstrate that C# is typesafe and how you use the DataReader.GetXY methods.

like image 142
Tim Schmelter Avatar answered Nov 10 '22 00:11

Tim Schmelter


Instead of any Array you can load your data in DataTable like:

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);         }     } } 

You can also use SqlDataAdapater to fill your DataTable like

SqlDataAdapter da = new SqlDataAdapter(command); da.Fill(dt); 

Later you can iterate each row and compare like:

foreach (DataRow dr in dt.Rows) {     if (dr.Field<string>("col1") == "yourvalue") //your condition     {     } } 
like image 33
Habib Avatar answered Nov 09 '22 23:11

Habib