If I'm using a parameterized query (ASP.NET with C#) in SQL, such as
var db = Database.Open("Database1");
SqlCommand cmd = new SqlCommand("SELECT * FROM pageinfo WHERE pageID = #pageID");
cmd.Parameters.AddWithValue("#pageID", 1);
And later on in the page, I want to do a foreach loop of whatever data was retrieved:
foreach(var row in ???)
What would I use (in place of the ???) to access the data I just retrieved?
Thanks.
It depends on how you execute a query.
Usually it's done by SqlCommand.ExecuteReader
For example, in your case, you can:
....
SqlDataReader reader = cmd .ExecuteReader();
while (reader.Read())
{
...
}
But there are also other ways to rertieve the data, for example using DataSet
For a complete example on how to do that can have a look on:
Using ADO.NET for beginners
You can use while iteration statement with SqlCommand.ExecuteReader instead of foreach. Take a look this;
var db = Database.Open("Database1");
SqlCommand cmd = new SqlCommand("SELECT * FROM pageinfo WHERE pageID = #pageID");
cmd.Parameters.AddWithValue("#pageID", 1);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader[0]);
}
reader[0] returns first row of first column and reader[1] returns first row of second column if your data has of course.
Related
I have a SQL query which supposed to return only ONE row from the business database. Based on this, I have written following sql script to get the data from the result set.
string query = #"select
ProdMaster.data_Id Id,
ProdMaster.data_name Name,
ProdMaster.data_countryname CountryName
from RM.Db
order by ProdMaster.data.FromDate desc"
SqlCommand command = new SqlCommand(query, conn);
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
countryname = reader["CountryName"].ToString();
}
}
But, there is some data issue in the database, sometimes it returns multiple rows.
How do we check the row count? If rows more than one we want to return a custom exception.
Note:
I do not want to use COUNT(*) in the query.
We don't have control on RM.Db database - it might have data issues (3rd party)
Don't you consider the next approach to solve your problem:
SqlCommand command = new SqlCommand(query, conn);
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
countryname = reader["CountryName"].ToString();
}
// Try to read the second row.
if (reader.Read())
{
// If we are inside this if-statement then it means that the query has returned more than one row.
// Here a custom exception must be thrown.
}
}
You can use SqlDataAdapter instead and fill the contents from the table in a dataset. The dataset will have a table inside it you can count the row like this - ds.Tables[0].Rows.Count
There can be problems related to Datareader as it is a stream of data and db can have changes while reading. A more thorough discussion on the same can be found on this thread -
How to get number of rows using SqlDataReader in C#
Hello everyone I am currently working on some testing project and I am having a little problem. Using selenium, I need to SendKey in specific element but instead of fixed value i need to use value (data) from my database. Can anyone help me with how to retrieve single value from database and store it in a variable so i can use it later.
Thank you and sorry for a noobish question - see code below:
SqlConnection conn = new SqlConnection();
SqlCommand command;
SqlDataReader dataReader;
conn.ConnectionString = "Server=******;Database=****;User ID=sqlserver;password=****;MultipleActiveResultSets=true;");
string query = "select RequestID, from AutomaticPayment where RequestID ='1230322'";
DataTable dt = new DataTable();
command = new SqlCommand(query, conn);
conn.Open();
dataReader = command.ExecuteReader();
dt.Load(dataReader);
driver.FindElement(By.Id("requestID")).SendKeys(VALUE FROM DATABASE);
You can use the following code
using (SqlConnection connection = new SqlConnection(_connectionString))
{
SqlDataAdapter sda = new SqlDataAdapter(query, connection);
connection.Open();
SqlCommand cmd = new SqlCommand(query, connection);
try
{
result = cmd.ExecuteScalar().ToString();
}
catch(NullReferenceException n)
{
result = "";
}
}
ExecuteScaler gets you the first column of the first row and additional columns are ignored. Use the value from result in your SendKeys()
Use conditions to limit the result:
Select data
SELECT TOP 1 RequestID FROM AutomaticPayment // Always returns 1 row
Or
SELECT RequestID FROM AutomaticPayment WHERE Id = 123 // Id must be unique to return 1 row
And maybe other ways.
Get value
var value = dt.Rows[0][1];
Or
var value = dt.Rows[0]["RequestID"];
From what i worked on with SqlCommand just do the following :
int yourId = 0;
dataReader = command.ExecuteReader()
while(dataReader.Read())
{
yourId = dataReader.GetInt32(0);
}
With that, you should have your value set to the first column of the dataReader. (that is selected thanks to your query, since you are requesting on a specific id, i guess it will return only one column
there is many other type available for Reader : Reader Microsoft Doc
And if you have in the futur many data to collect, use the ORM entity framework, work well for me
Source
EDIT :
Since you are only querying one data, maybe the solution of #work_ishaan is better than mine in this case, check it out.
Here I came up with situation where I want insert records in temp temple and again want to dispaly that record to user.
I have created one sp in that sp created temp table, added record to that table and select record from temp table.How to show record to user in interface?
ExecuteNOnquery is used for inserting record and ExecuteReader is is used for selecting record.
Withing same sp,I have insert and select.So how to do that in code behind?
You should use ExecuteReader.
All it does - sends string of CommandText to server, executes it, and then builds SqlDataReader to read from.
So if your CommandText is a call to stored procedure - this procedure will be executed (so it will insert your data and select it back) and returned data will be available in SqlDataReader.
See MSDN for reference to ExecuteReader
You could do something like this
using(var con = new SqlConnection(conStr))
{
var cmd = new SqlCommand("MY_SP",con);
cmd.CommandType = CommandType.StoredProcedure;
var da = new SqlDataAdapter(cmd);
var ds = new DataSet();
da.Fill(ds);
if(ds.Tables.Count > 0)
{
foreach(var dr in ds.Tables[0].Rows)
{
// Do stuffs with dr
}
}
}
I have an SQL query as follows:
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT id FROM Pages WHERE pageName=about",conn);
//cmd.Parameters.Add("#pageName","hakkinda");
SqlDataReader reader = cmd.ExecuteReader();
flID = reader.GetInt16(0);
reader.Close();
conn.Close();
I get an error message:
Invalid attempt to read when no data is present.
What's wrong?
I notice a couple potential issues:
You need to call reader.Read(), before trying to read data from it. This is usually done in a loop when people expect multiple rows.
while (reader.Read()) {
flID = reader.GetInt16(0);
}
also in your SQL if "about" is meant to be a literal and not another column name you probably need single quotes around it:
"SELECT id FROM Pages WHERE pageName='about'"
Your query is returning 0 results. This is because the parameter value in the SQL string is missing quotes. It should read as follows (notice the single quotes around the word 'about'):
SqlCommand cmd = new SqlCommand("SELECT id FROM Pages WHERE pageName='about'",conn);
You have to call DataReader.Read to fetch the result:
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
DataReader.Read returns a boolean, so if you have more than 1 result, you can do:
while (reader.Read()) {
// read data here
}
Your select statement should be:
"SELECT id FROM Pages WHERE pageName='about'"
If you expect only single value to be returned, you can use .ExecuteScalar()
flID = int.Parse(query.ExecuteScalar().ToString());
Also, use single quotation marks for pageName value.
SqlCommand cmd = new SqlCommand("SELECT id FROM Pages WHERE pageName='about';",conn);
I'm using C# in VS 2005 (.NET 2.0) and SQL Studio 2005 on an older CMS made in the mid-'00s. I'm tasked with creating a new permission gate that allows only certain users to see certain parts of the site.
I need help populating a List list based on feedback I got when I posted this question: Populate ArrayList from Stored Procedure result set
So, now, how do get get the values from the stored procedure into a List? I realize this is a novice question but I'm a novice...
Any help is greatly appreciated.
Assuming you are getting your results from a DataReader, all you have to do is read each row to add the value to a list.
List<int> ReadList(IDataReader reader)
{
List<int> list = new List<int>();
int column = reader.GetOrdinal("MyColumn");
while (reader.Read())
{
list.Add(reader.GetInt32(column));
}
return list;
}
Remember to dispose of the DataReader when you are done with it.
You can try using the model located on this MSDN page under Using Parameters with a SqlCommand and a Stored Procedure. The example is shown here:
static void GetSalesByCategory(string connectionString, string categoryName)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Create the command and set its properties.
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "SalesByCategory"; //Stored Procedure Name
command.CommandType = CommandType.StoredProcedure;
// Add the input parameter and set its properties.
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "#CategoryName";
parameter.SqlDbType = SqlDbType.NVarChar;
parameter.Direction = ParameterDirection.Input;
parameter.Value = categoryName;
// Add the parameter to the Parameters collection.
command.Parameters.Add(parameter);
// Open the connection and execute the reader.
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
//Instead of displaying to console this is where you would add
// the current item to your list
Console.WriteLine("{0}: {1:C}", reader[0], reader[1]);
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
}
}
it depends on how you have retreived the results
reader?
dataset?
something else?
walk through the results using
foreach (int item in object...) {
List.Add(item);
}
or possibly (I dont remember the exact DataRow syntax off the top of my head...)
foreach (datarow row in object.table[0].rows) {
List.Add(row[0]);
}
IList<int> myInts = new List<int>();
using (IDbConnection connection = new SqlConnection("yourConnectionStringGoesHere"))
{
using (IDbCommand command = new SqlCommand("spName", connection))
{
command.CommandType = CommandType.StoredProcedure;
//command.Parameters.Add(...) if you need to add any parameters to the SP.
connection.Open();
using (IDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection))
{
myInts.Add(Int32.Parse(reader["someIntField"].ToString()));
}
}
}
Since you already have the table the idea would be to iterate over that table while adding the IDs of the vendor into a list.
List<VendorID_Data_Type> myList = new List<VendorID_Data_Type>();
foreach(DataRow r in GetAllVendors().Rows)
{
myList.Add(r["VendorID"]);
}
What I ended up doing is using a DataTable as an intermediary data type, which is populated by the stored procedure. Then, refactoring the DataTable as the data-source in a foreach loop, I populated the List. I needed to open a second question to get to this conclusion: 2-Column DataTable to List<int> .NET 2.0