Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
SQL
var q = db.Execute("a select query");


Hi! I wana access the columns (and rows) obtained from this query (like q[0].column1). But when I store it in a var it is not possible. What kind of datatype or technique can I use? Is there a difference between single row output and multiple row output when doing this? Im working with sql server CE db (sdf file) in webmatrix.
Posted
Updated 25-Dec-12 22:47pm
v2

if you are working in asp.net with c# :


C#
using(SqlConnection con = new SqlConnection(connectionstring))
{
  con.Open();

  SqlCommand cmd = new SqlCommand("SELECT * FROM tableName", con);
  SqlDataadapter adpt = new SqlDataAdapter(cmd);

  DataSet ds = new DataSet();
  adpt.Fill(ds);

  DataColumn dclA = ds.Tables[0].Columns[0];
  // OR
  DataColumn dclB = ds.Tables[0].Columns["ColumnName"];

  DataRow drA = ds.Tables[0].Rows[0];

  string DataA = drA["ColumnName"].ToString();
  // OR
  string DataB = drA[0].ToString();
}


Try it...
 
Share this answer
 
v3
Comments
AshishChaudha 27-Dec-12 23:41pm    
my +5!
Try this.


C#
SqlCommand command = new SqlCommand();
command.Connection = sqlCon;
command.CommandType = CommandType.Text;
command.CommandTimeout = 216000;
command.CommandText = "Your Query";
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataTable dt = new DataTable();
adapter.Fill(dt);

string dataValue = dt.Rows[0]["Column_Name"]; // returns First Rows



Hope it helps you.
 
Share this answer
 
HI,

Refer the following links these may help you.

C# DataTable
Dataset
DATATABLE and DATASET

These are the different ways that you can access the columns and rows.

Thanks
 
Share this answer
 
The first problem in your question is the way you queries a Database object in Web Pages.
As you can see (Database Class[^]) there are three methods to execute a query:
Query, to obtain a list of rows as IEnumerable<object>;
QuerySingle, to obtain a single row as object;
QueryValue, to obtain a single scalar value.
The Execute method executes a non-query SQL statement, instead.
So, if you want to obtain a list of row you should query your database with this statement:
C#
var q = db.Query("SELECT ... ");

and if you want to obtain your rows sequentially you should use this block of code:
C#
@foreach(var row in q){
   <p>row.FieldName</p>
}

Otherwise, if you want to access your rows randomly, you should convert the IEnumerable to a List:
C#
var q = db.Query("SELECT ... ").ToList();

and then you can use statements like
C#
<p>@q[20].FieldName</p>
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900