Datareader and list - c#

I am trying to create a list as below and updating it with values from the datareader. I need help in writing the code to update this list from the data reader.
internal IList<FilingDto> LoadStatusDtofromReader(IDataReader reader)
{
IList<FilingDto> filingstatus = new List<FilingDto>();
while (reader !=null && reader.Read())
{
var dto = new FilingDto();
var Year = (Decimal)reader["Year"];
dto = new FilingDto()
{
Controllerid = (Guid)reader["Collectorid"],
Status = DBNull.Value.Equals(reader["Status"]) ? string.Empty : reader["Status"].ToString(),
Year = Convert.ToInt32(Year),
Level = DBNull.Value.Equals(reader["Level"]) ? string.Empty : reader["ServiceLevel"].ToString()
};
filingstatus.Add(dto);
}
return status;
}
The code to read from the datareader is as below but i am stuck in between please help me complete this
DataTable FilingStatus = new DataTable("FilingStatus");
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Connectionstring"].ConnectionString);
sqlcon.Open();
SqlCommand cmd = new SqlCommand("select Collectorid, Status, Year, Level from dbo.abc", sqlcon);
using (IDataReader dr =

You should invoke ExecuteReader on SqlCommand object
SqlCommand cmd = new SqlCommand("select Collectorid, Status, Year, Level from dbo.abc", sqlcon);
SqlDataReader reader = cmd.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
I suggest to use ORM like Entity framework instead ADO.NET

Try this,
DataTable FilingStatus = new DataTable("FilingStatus");
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["CentralW2Database"].ConnectionString);
sqlcon.Open();
SqlCommand cmd = new SqlCommand("select CollectorGuid, FileStatus,FilingYear, ServiceLevel from dbo.FilingRequestQueue", sqlcon);
using (var dr = cmd.ExecuteReader())
{
IList<FilingDto> list = LoadStatusDtofromReader(dr);
}
internal IList<FilingDto> LoadStatusDtofromReader(IDataReader reader)
{
var filingstatus = new List<FilingDto>();
while (reader != null && reader.Read())
{
var dto = new FilingDto
{
Controllerid = (Guid)reader["Collectorid"],
Status = DBNull.Value.Equals(reader["Status"]) ? string.Empty : reader["Status"].ToString(),
Year = Convert.ToInt32((Decimal)reader["Year"]),
Level = DBNull.Value.Equals(reader["Level"]) ? string.Empty : reader["ServiceLevel"].ToString()
};
filingstatus.Add(dto);
}
return filingstatus;
}

If you can reuse the original function just do
using (DataReader dr = cme.ExecuteReader())
{
IList<FilingDto> list = LoadStatusDtofromReader(dr);
}

Related

How to concatenate query result in C#

I want to concatenate the query result in c#. Below is the resulting image
In my code, I have done
using (MySqlConnection cn = new MySqlConnection(conn.ConnectionString))
{
string query = "SELECT m.`read_param` FROM mdc_request m WHERE m.`row_id` = #row_id";
cn.Open();
MySqlCommand cmd = new MySqlCommand(query, cn);
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#row_id", iterations.row_id);
reader = cmd.ExecuteReader();
while (reader.Read())
{
// here I want to save the result in one single variable
}
}
Update 1
As per #Rahul answer, I have done the following
public async Task YtlbusMethod(List<Iterations> ytlbus)
{
MySqlConnection cn = null;
int limitRequest = 10;
for (int i = 10; i > 0; i--)
{
foreach (var item in ytlbus)
{
using (cn = new MySqlConnection(conn.ConnectionString))
{
string query = "SELECT m.`time` FROM `mdc_meter_config` m WHERE m.`row_id` = #row_id";
cn.Open();
MySqlCommand cmd = new MySqlCommand(query, cn);
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#row_id", item.row_id);
reader = cmd.ExecuteReader();
while (reader.Read())
{
string time = (string)reader["time"];
if(item.time == time)
{
int sleeptime = Convert.ToInt32(item.time);
sleeptime = sleeptime * 1000;
Thread.Sleep(sleeptime);
Task.Factory.StartNew(() => PortHitmethod(item));
}
}
}
cn.Close();
// select query kerni hy ..jis main wohi data ay jo tu yahan pass ker raha hy... where k ander just tuny row id pass kerni hy.
//if(item.time== query main jo time aya hy woh)
//{
//}
}
}
}
public async Task PortHitmethod(Iterations iterations)
{
MySqlConnection cn = null;
List<string> data = new List<string>();
using (cn = new MySqlConnection(conn.ConnectionString))
{
string query = "SELECT m.`read_param` FROM mdc_request m WHERE m.`row_id` = #row_id";
cn.Open();
MySqlCommand cmd = new MySqlCommand(query, cn);
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#row_id", iterations.row_id);
reader = cmd.ExecuteReader();
while (reader.Read())
{
data.Add(reader["read_param"].ToString());
}
}
cn.Close();
var single = string.Join("", data);
}
Now the issue that I am facing is that I am unable to get all the rows data. The total rows are 9 but I am getting less than that
How can I achieve this? Any help would be highly appreciated.
Looks like those are integer value then you can do something like
List<int> data = new List<int>;
while (reader.Read())
{
data.Add(int.Parse(reader["read_param"].ToString()));
}
Then you can use string.Join() method like
var single = string.Join(",", data);
Based on #Rahul, your code should be:
Your update 1 is different code.
What do you want to achieve here.
List<string> data = new List<string>();
using (MySqlConnection cn = new MySqlConnection(conn.ConnectionString))
{
string query = "SELECT m.`read_param` FROM mdc_request m WHERE m.`row_id` = #row_id";
cn.Open();
MySqlCommand cmd = new MySqlCommand(query, cn);
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#row_id", iterations.row_id);
reader = cmd.ExecuteReader();
while (reader.Read())
{
data.Add(reader["read_param"].ToString());
}
}
var single = string.Join("", data);

How to return list of records using stored procedure and datareader in C#

I want to return list of records using stored procedure and datareader in C#. Currently, it is giving me error
Cannot implicitly convert type 'ClsHorseTracker' to 'System.Collections.Generic.List'
Code:
public List<ClsHorseTracker> HorseTrackerList()
{
clsUtilities clsUtilities = new clsUtilities();
DataSet ds;
List<ClsHorseTracker> clsHorseTracker = new List<ClsHorseTracker>();
string sSQL = "exec HorseDetails";
ds = clsUtilities.GetDataSet(sSQL);
SqlCommand cmd = new SqlCommand();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
clsHorseTracker = new ClsHorseTracker
{
HorseName = Convert.ToString(reader["HorseName"]),
HorseTypeName = Convert.ToString(reader["HorseTypeName"]),
};
}
}
}
return clsHorseTracker;
}
clsHorseTracker is a list of ClsHorseTracker. So you need to add new object to the list in "while" loop instead of assign an object to the list
Try this
public List<ClsHorseTracker> HorseTrackerList()
{
clsUtilities clsUtilities = new clsUtilities();
DataSet ds;
List<ClsHorseTracker> clsHorseTracker = new List<ClsHorseTracker>();
string sSQL;
sSQL = "exec HorseDetails";
ds = clsUtilities.GetDataSet(sSQL);
SqlCommand cmd = new SqlCommand();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
clsHorseTracker.Add(new ClsHorseTracker
{
HorseName = Convert.ToString(reader["HorseName"]),
HorseTypeName = Convert.ToString(reader["HorseTypeName"]),
});
}
}
}
return clsHorseTracker;
}

How to get particular value from SqlCommand

I want to store values of SqlCommand in string variable and print it on label. Here is my C# code
String sq="select fullname,emailId from Registration where RgId= '"+Session["RgId"]+"'";
SqlCommand cmd1 = new SqlCommand(sq, con);
con.Open();
SqlDataReader rdr = null;
rdr = cmd1.ExecuteReader();
while(rdr.Read())
{
string fname = (string)rdr["fullname"];
string femail=(string)rdr["emailId"];
Label4.Text = fname;
label5.Text=femail;
}
if(rdr!= null)
{
rdr.Close();
}
con.Close();
but instead of printing value it doesn't show value on label. What to do? Is there anything wrong in code?
I would recommend using using statements when dealing with db access. Things get cleaned up better this way. Since your not using a try/catch in the code provided I would assume your using it in an outer layer or something so I would:
if (Session["RgId"] == null)
throw new NullReferenceException("RgId");
using (var con = new SqlConnection())
{
const string sql = "select fullname,emailId from Registration where RgId = #RgId";
using (var cmd1 = new SqlCommand(sql, con))
{
cmd1.Parameters.Add(new SqlParameter("RdId", SqlDbType.Int) {Value = Session["RgId"]});
con.Open();
using (var rdr = cmd1.ExecuteReader(CommandBehavior.CloseConnection))
{
if (rdr.Read())
{
Label4.Text = (string) rdr["fullname"];
label5.Text = (string) rdr["emailId"];
}
else
{
//handle registration not found
}
rdr.Close();
}
}
}
To make SQL queries, not concatenate a string, this is very dangerous for your system facilitating SQL injections.
Validate your values before attempting to query and validate the query returns.
if (Session["RgId"] != null && !String.IsNullOrEmpty(Session["RgId"].ToString()))
{
String sq = "select fullname,emailId from Registration where RgId = #RgId";
SqlCommand cmd1 = new SqlCommand(sq, con);
cmd1.Parameters.Add("#RgId", Convert.ToInt32(Session["RgId"].ToString()));
con.Open();
SqlDataReader rdr = cmd1.ExecuteReader();
if (rdr != null)
{
while (rdr.Read())
{
if (rdr["fullname"] != DBNull.Value && rdr["emailId"] != DBNull.Value)
{
Label4.Text = rdr["fullname"].ToString();
label5.Text = rdr["emailId"].ToString();
}
}
}
if (rdr != null)
{
rdr.Close();
}
con.Close();
}
Regards,
Andrew

DataReader.Read() always returns false

I've been searching for hours now. I can't find anything helpful for my problem.
The Read()-function always returns false. If I run the SQL-command with sqlplus I get this result:
GERA_ID GETY_BEZEICHNUNG
---------------------------
100001 Blackberry
100002 GSM
here's a simplified version of the code:
List<Divice> divices = new List<Divice>();
using (OracleConnection connection = new OracleConnection(connectionString))
{
OracleCommand cmd = new OracleCommand("select gera_id, gety_bezeichnung from idc_geraet, idc_geraettyp where idc_geraettyp.gety_id = idc_geraet.gety_id and pers_id = 4711");
cmd.Connection = connection;
connection.Open();
OracleDataReader reader = cmd.ExecuteReader();
while(reader.Read()) //returns always false
{
Divice g = new Divice();
g.gera_id = reader.GetDecimal(0);
g.gety_bezeichnung = reader.GetString(1);
divices.Add(g);
}
reader.Close();
}
EDIT:
This Code is called before. and it works fine:
IDC_PERSON p = new IDC_PERSON();
using (OracleConnection connection = new OracleConnection(connectionString))
{
OracleCommand cmd = new OracleCommand("select PERS_VNAME, PERS_NNAME, PERS_EINTRDATUM from idc_person where PERS_ID = 4711");
cmd.Connection = connection;
connection.Open();
OracleDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (reader.Read())
{
p.PERS_ID = user_id;
p.PERS_VNAME = reader.GetString(0);
p.PERS_NNAME = reader.GetString(1);
p.PERS_EINTRDATUM = reader.GetDateTime(2);
}
reader.Close();
}
So, here is the whole code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Oracle.DataAccess.Client;
using TelKoOpt.Models;
using System.Data;
namespace TelKoOpt.Controllers
{
public class HomeController : Controller
{
string connectionString = "user id=scott;password=tiger;" +
"data source=(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=localhost)" +
"(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orcl)))";
public ActionResult Index(int user_id)
{
MyDbContext dbcontext = new MyDbContext();
IDC_PERSON p = new IDC_PERSON();
List<IDC_GERAET> geraete = new List<IDC_GERAET>();
List<TELGSMEGN> telgsmegn = new List<TELGSMEGN>();
dbcontext.pers = p;
dbcontext.geraete = geraete;
dbcontext.telgsmegn = telgsmegn;
using (OracleConnection connection = new OracleConnection(connectionString))
{
OracleCommand cmd = new OracleCommand("select PERS_VNAME, PERS_NNAME, PERS_EINTRDATUM from idc_person where PERS_ID = " + user_id);
//OracleCommand cmdTelg = new OracleCommand("select service, sum(betrag), sum(dauer), sum(anzahl), zonen from test_telgsmegn where gera_id = " + user_id + " and datumaktion between '" + "01.02.2012" + "' and '" + "20.03.2012" + "' group by service, zonen; ");
cmd.Connection = connection;
//cmdTelg.Connection = new OracleConnection(connectionString);
try
{
connection.Open();
OracleDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
p.PERS_ID = user_id;
p.PERS_VNAME = reader.GetString(0);
p.PERS_NNAME = reader.GetString(1);
p.PERS_EINTRDATUM = reader.GetDateTime(2);
}
reader.Close();
}
catch (OracleException)
{
//return View(dbcontext);
}
}
using (OracleConnection connection = new OracleConnection(connectionString))
{
OracleCommand cmd = new OracleCommand("select gera_id, gety_bezeichnung from idc_geraet, idc_geraettyp where idc_geraettyp.gety_id = idc_geraet.gety_id and pers_id = " + user_id);
cmd.Connection = connection;
try
{
connection.Open();
OracleDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
IDC_GERAET g = new IDC_GERAET();
g.gera_id = reader.GetDecimal(0);
g.gety_bezeichnung = reader.GetString(1);
geraete.Add(g);
}
reader.Close();
}
catch (OracleException)
{
//return View(dbcontext);
}
}
return View(dbcontext);
}
}
}
This may not be the answer for your case, but I ran into a similar issue when debugging code and it may help others who come across this question.
The solution I figured out was actually only specific to when you are debugging. When stepping through code, if you expand the "Results View" (which enumerates the enumerable), when you get to the part in your code that reads the data reader, the reader will already be at the end of the results, and will return false. This is because data readers are forward only, and once you've enumerated to the next result (which was done by the debugger in this case), you can't go back.
same issue faced by me this is how i fixed
use out type
public void ExecuteStoredProcReturnDataReader(string sQueryName, out IDataReader dr, List<DBParam> oParams =null)
{
try
{
dbHelper DBProvider = new dbHelper();
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
oCmd = DBProvider.CreateCommand(sQueryName, conn);
if (oParams !=null)
DBProvider.CreateParameters(oParams, ref oCmd);
dr = oCmd.ExecuteReader();
}
catch (Exception e)
{
rethrow = DataAccessExceptionHandler.HandleException(ref e);
if (rethrow)
{
throw e;
}
dr = null;
}
}

How to generate List<String> from SQL query?

If I have a DbCommand defined to execute something like:
SELECT Column1 FROM Table1
What is the best way to generate a List<String> of the returned records?
No Linq etc. as I am using VS2005.
I think this is what you're looking for.
List<String> columnData = new List<String>();
using(SqlConnection connection = new SqlConnection("conn_string"))
{
connection.Open();
string query = "SELECT Column1 FROM Table1";
using(SqlCommand command = new SqlCommand(query, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
columnData.Add(reader.GetString(0));
}
}
}
}
Not tested, but this should work fine.
Loop through the Items and Add to the Collection. You can use the Add method
List<string>items=new List<string>();
using (var con= new SqlConnection("yourConnectionStringHere")
{
string qry="SELECT Column1 FROM Table1";
var cmd= new SqlCommand(qry, con);
cmd.CommandType = CommandType.Text;
con.Open();
using (SqlDataReader objReader = cmd.ExecuteReader())
{
if (objReader.HasRows)
{
while (objReader.Read())
{
//I would also check for DB.Null here before reading the value.
string item= objReader.GetString(objReader.GetOrdinal("Column1"));
items.Add(item);
}
}
}
}
Or a nested List (okay, the OP was for a single column and this is for multiple columns..):
//Base list is a list of fields, ie a data record
//Enclosing list is then a list of those records, ie the Result set
List<List<String>> ResultSet = new List<List<String>>();
using (SqlConnection connection =
new SqlConnection(connectionString))
{
// Create the Command and Parameter objects.
SqlCommand command = new SqlCommand(qString, connection);
// Create and execute the DataReader..
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
var rec = new List<string>();
for (int i = 0; i <= reader.FieldCount-1; i++) //The mathematical formula for reading the next fields must be <=
{
rec.Add(reader.GetString(i));
}
ResultSet.Add(rec);
}
}
If you would like to query all columns
List<Users> list_users = new List<Users>();
MySqlConnection cn = new MySqlConnection("connection");
MySqlCommand cm = new MySqlCommand("select * from users",cn);
try
{
cn.Open();
MySqlDataReader dr = cm.ExecuteReader();
while (dr.Read())
{
list_users.Add(new Users(dr));
}
}
catch { /* error */ }
finally { cn.Close(); }
The User's constructor would do all the "dr.GetString(i)"
Where the data returned is a string; you could cast to a different data type:
(from DataRow row in dataTable.Rows select row["columnName"].ToString()).ToList();
This version has the same purpose of #Dave Martin but it's cleaner, getting all column, and easy to manipulate the data if you wan't to put it on Email, View, etc.
List<string> ResultSet = new List<string>();
using (SqlConnection connection = DBUtils.GetDBConnection())
{
connection.Open();
string query = "SELECT * FROM DATABASE";
using (SqlCommand command = new SqlCommand(query, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
var rec = new List<string>();
for (int i = 0; i <= reader.FieldCount - 1; i++)
{
rec.Add(reader.GetString(i));
}
string combined = string.Join("|", rec);
ResultSet.Add(combined);
}
}
}
}

Categories

Resources