Returning the last row in webservice - c#

Im trying to to get all of my table records using webservice. I tried this :
public class Student
{
public int id;
public string name;
public string grade;
}
[WebMethod]
public Student[] getall()
{
Student objStd = new Student();
Student[] stds = new Student[400];
SqlConnection conn;
conn = Class1.ConnectionManager.GetConnection();
conn.Open();
SqlCommand newCmd = conn.CreateCommand();
newCmd.CommandType = CommandType.Text;
newCmd.CommandText = "select * from dbo.tblUser";
SqlDataReader sdr = newCmd.ExecuteReader();
for (int runs = 0; sdr.Read(); runs++)
{
objStd.id = Int32.Parse(sdr["Id"].ToString());
objStd.name = sdr["name"].ToString();
objStd.grade = sdr["grade"].ToString();
stds[runs] = objStd;
}
conn.Close();
sdr.Close();
return stds;
}
but the result of this is like this:
<?xml version="1.0" encoding="UTF-8"?>
<ArrayOfStudent xmlns="http://tempuri.org/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
-<Student>
<id>8</id>
<name>hhhhh</name>
<grade>76</grade>
</Student>
-<Student>
<id>8</id>
<name>hhhhh</name>
<grade>76</grade>
</Student>
-<Student>
<id>8</id>
<name>hhhhh</name>
<grade>76</grade>
</Student>
-<Student>
<id>8</id>
<name>hhhhh</name>
<grade>76</grade>
</Student>
....
this will return only the last record again and again, why?
what should I correct in my code?

Make a List add to it and return, now you are returning only the last object.
Create the Student Object instance inside the For Loop
List<Student> stds = new List<Student>();
for (int runs = 0; sdr.Read(); runs++)
{
Student objStd = new Student();
objStd.id = Int32.Parse(sdr["Id"].ToString());
objStd.name = sdr["name"].ToString();
objStd.grade = sdr["grade"].ToString();
stds.Add(objStd);
}

Create objStudent inside the loop so you don't keep updating the same student
[WebMethod]
public Student[] getall()
{
Student[] stds = new Student[400];
SqlConnection conn;
conn = Class1.ConnectionManager.GetConnection();
conn.Open();
SqlCommand newCmd = conn.CreateCommand();
newCmd.CommandType = CommandType.Text;
newCmd.CommandText = "select * from dbo.tblUser";
SqlDataReader sdr = newCmd.ExecuteReader();
for (int runs = 0; sdr.Read(); runs++)
{
Student objStd = new Student();
objStd.id = Int32.Parse(sdr["Id"].ToString());
objStd.name = sdr["name"].ToString();
objStd.grade = sdr["grade"].ToString();
stds[runs] = objStd;
}
conn.Close();
sdr.Close();
return stds;
}

If your count of student is dynamic use list instead of array with static lenght. Also you must create student object when you read new record from Reader.
[WebMethod]
public Student[] getall()
{
List<Student> studentList=new List<Student>();
SqlConnection conn;
conn = Class1.ConnectionManager.GetConnection();
conn.Open();
SqlCommand newCmd = conn.CreateCommand();
newCmd.CommandType = CommandType.Text;
newCmd.CommandText = "select * from dbo.tblUser";
SqlDataReader sdr = newCmd.ExecuteReader();
while(sdr.Read()){
Student student= new Student();
student.id = Int32.Parse(sdr["Id"].ToString());
student.name = sdr["name"].ToString();
student.grade = sdr["grade"].ToString();
studentList.Add(student);
}
conn.Close();
sdr.Close();
return studentList.ToArray();
}

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

Unable to show extracted data from the table in fiddler

I have written the following code to extract all records from the table in the SQL server. There is no error in the code but when I run it in fiddler, I am getting null objects.
[HttpGet]
public List<Student> Get()
{
SqlDataReader reader = null;
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = #"Data Source=PALLAVI-PC\SQLEXPRESS;Initial Catalog=StudentDB;Integrated Security=True;MultipleActiveResultSets=True;";
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select * from Tbl_Students;";
sqlCmd.Connection = myConnection;
myConnection.Open();
reader = sqlCmd.ExecuteReader();
int rowCount = 0;
while (reader.Read())
{
rowCount++;
}
Student[] student = new Student[rowCount];
for(int i=0;i<rowCount;i++)
{
student[i] = new Student();
}
int j = 0;
while (reader.Read())
{
// student[j] = new Student();
student[j].Roll_Number = Convert.ToInt32(reader.GetValue(0));
student[j].FirstName = reader.GetValue(1).ToString();
student[j].LastName = reader.GetValue(2).ToString();
student[j].Class = Convert.ToInt32(reader.GetValue(3));
student[j].Gender = reader.GetValue(4).ToString();
j++;
}
return student.ToList();
myConnection.Close();
}
I have 5 records in the table. I am able to get 5 json objects but without the content.
Attaching the image from Fiddler:
Student.cs
namespace WebAPIDemo.Models
{
public class Student
{
public int Roll_Number { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Class { get; set; }
public string Gender { get; set; }
}
}
Try this, without taking count of records. I'm not using the array, I have created new instance of student for each record.
public static List<Student> GetData()
{
List<Student> lstStudent = new List<Student>();
using (SqlConnection con = new SqlConnection(#"Data Source=PALLAVI-PC\SQLEXPRESS;Initial Catalog=StudentDB;Integrated Security=True;MultipleActiveResultSets=True;"))
{
using (SqlCommand cmd = new SqlCommand("Select * from Tbl_Students;", con))
{
cmd.CommandType = CommandType.Text;
if (con.State == ConnectionState.Closed)
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
Student student =new Student();
student.Roll_Number = Convert.ToInt32(reader.GetValue(0));
student.FirstName = reader.GetValue(1).ToString();
student.LastName = reader.GetValue(2).ToString();
student.Class = Convert.ToInt32(reader.GetValue(3));
student.Gender = reader.GetValue(4).ToString();
lstStudent.Add(student);
}
}
}
return lstStudent;
}
your first while(reader.Read()) is the actual reader object with data. DataReader allows forward only read only access to a data row.The next while loop won't even execute because the Read() is already completed.So you're getting an array of 5 Student objects that are initialized with default values.
Instead of initializing an array of Student populate instances and add to a List<Student> inside the while loop.

List is empty at the return statement MVC

I have a form where the user searched for a customer's account by name, ssn, old account number, etc. When I am populating the list in the while loop, the values are present, however when it exits the loop, in the return statement the count is 0. Any idea why I am loosing the values?
Function creating the list:
public static List<Account> GetAccountNumbersFromCustomerSSN(string CustomerSSN)
{
List<Account> accts = new List<Account>();
try
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TA_connectionstring"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("spGet_Account_Numbers_From_SSN", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlParameter P1 = new SqlParameter("#CUSTOMER_SSN", DbType.String);
P1 = new SqlParameter("#CUSTOMER_SSN", DbType.String);
P1.Value = CustomerSSN;
cmd.Parameters.Add(P1);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Account acct = new Account
{
OriginalAcctNumber = dr["TABOAT_ACCOUNT_NUMBER"].ToString().TrimStart('0'),
FTBOATAcctNumber = dr["FTBOAT_ACCOUNT_NUMBER"].ToString().TrimStart('0'),
SSN = CustomerSSN.Substring(CustomerSSN.Length -4).PadLeft(CustomerSSN.Length, '*'),
CustomerName = dr["CUST_NAME"].ToString(),
ProductType = dr["TRGT_PROD"].ToString()
};
}
con.Close();
}
}
catch (Exception ex)
{
ExceptionUtility.LogException(ex, "GetCustomerSSN()");
}
return accts;
}
You're not adding the acct to the list of Accounts.
while (dr.Read())
{
Account acct = new Account
{
OriginalAcctNumber = dr["TABOAT_ACCOUNT_NUMBER"].ToString().TrimStart('0'),
FTBOATAcctNumber = dr["FTBOAT_ACCOUNT_NUMBER"].ToString().TrimStart('0'),
SSN = CustomerSSN.Substring(CustomerSSN.Length -4).PadLeft(CustomerSSN.Length, '*'),
CustomerName = dr["CUST_NAME"].ToString(),
ProductType = dr["TRGT_PROD"].ToString()
};
accts.Add(acct); // You're missing this line.
}
You're not adding the acct to the accts list!
while (dr.Read())
{
Account acct = new Account
{
OriginalAcctNumber = dr["TABOAT_ACCOUNT_NUMBER"].ToString().TrimStart('0'),
FTBOATAcctNumber = dr["FTBOAT_ACCOUNT_NUMBER"].ToString().TrimStart('0'),
SSN = CustomerSSN.Substring(CustomerSSN.Length -4).PadLeft(CustomerSSN.Length, '*'),
CustomerName = dr["CUST_NAME"].ToString(),
ProductType = dr["TRGT_PROD"].ToString()
};
accts.Add(acct); // ADD THIS HERE
}
All depending on how you want to do it you can also return IEnumerable by:
public static IEnumerable<Account> GetAccountNumbersFromCustomerSSN
(string CustomerSSN)
{
List<Account> accts = new List<Account>();
try
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings
["TA_connectionstring"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("spGet_Account_Numbers_From_SSN", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlParameter P1 = new SqlParameter
("#CUSTOMER_SSN", DbType.String);
P1 = new SqlParameter
("#CUSTOMER_SSN", DbType.String);
P1.Value = CustomerSSN;
cmd.Parameters.Add(P1);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
yield return new Account
{
OriginalAcctNumber =
dr["TABOAT_ACCOUNT_NUMBER"].ToString().TrimStart('0'),
FTBOATAcctNumber =
dr["FTBOAT_ACCOUNT_NUMBER"].ToString().TrimStart('0'),
SSN =
CustomerSSN.Substring(CustomerSSN.Length -4).PadLeft(CustomerSSN.Length, '*'),
CustomerName =
dr["CUST_NAME"].ToString(),
ProductType =
dr["TRGT_PROD"].ToString()
};
}
con.Close();
}
}
catch (Exception ex)
{
ExceptionUtility.LogException(ex, "GetCustomerSSN()");
}
}

my class gives no value back that I can use

this is how I try to print something worthwhile for my site using my class, When I try to write my class will not find it at all.
I can not find my worth to return something worthwhile for my user.
the problem is that it can not find at all class.
My class:
public class AbonnementsId
{
public int indhold { get; set; }
}
public AbonnementsId HentAbonnementsId()
{
AbonnementsId AbonnementsidReturn = new AbonnementsId();
AbonnementsidReturn.indhold = 0;
SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
SqlCommand cmd1 = conn1.CreateCommand();
cmd1.Connection = conn1;
int brugerid = Convert.ToInt32(HttpContext.Current.Session["id"]);
cmd1.CommandText = #"SELECT abonnementsid from brugere WHERE id = #id";
cmd1.Parameters.AddWithValue("#id", brugerid);
conn1.Open();
SqlDataReader readerBrugerA = cmd1.ExecuteReader();
if (readerBrugerA.Read())
{
AbonnementsidReturn.indhold = Convert.ToInt32(readerBrugerA["abonnementsid"]);
}
conn1.Close();
return AbonnementsidReturn;
}
Here is how I write my class out when I need it for my content.
if (Session["AbonnementsId"] != null)
{
_subscriptionId = long.Parse(Session["AbonnementsId"].ToString());
}
else
{
//when I need to print my class do I like it here
_subscriptionId = AbonnementsidReturn.indhold();
}
I'm totally shooting in the dark here:
public static class AbonnementsId
{
public static int GetAbonnementsId()
{
int abonnementsid;
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
using(var conn = new SqlConnection(connectionString))
{
int brugerid = Convert.ToInt32(HttpContext.Current.Session["id"]);
SqlCommand cmd1 = conn.CreateCommand();
cmd1.Connection = conn;
cmd1.CommandText = #"SELECT abonnementsid from brugere WHERE id = #id";
cmd1.Parameters.AddWithValue("#id", brugerid);
conn.Open();
SqlDataReader readerBrugerA = cmd1.ExecuteReader();
if (readerBrugerA.Read())
abonnementsid = Convert.ToInt32(readerBrugerA["abonnementsid"]);
conn.Close();
}
return abonnementsid;
}
}
You can then call this in your code:
if (Session["AbonnementsId"] != null)
{
_subscriptionId = long.Parse(Session["AbonnementsId"].ToString());
}
else
{
//when I need to print my class do I like it here
_subscriptionId = AbonnementsId.GetAbonnementsId();
}

How to count the number of rows from sql table in c#?

How to count the number of rows from sql table in c#?
I need to extract some data from my database...
You may try like this:
select count(*) from tablename where columname = 'values'
C# code will be something like this:-
public int A()
{
string stmt = "SELECT COUNT(*) FROM dbo.tablename";
int count = 0;
using(SqlConnection thisConnection = new SqlConnection("Data Source=DATASOURCE"))
{
using(SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
{
thisConnection.Open();
count = (int)cmdCount.ExecuteScalar();
}
}
return count;
}
You need to make a database connection from c# first. Then, you need to pass below query as commandText.
Select count(*) from TableName
Use ExecuteScalar/ExecuteReader to get the returned count.
Do you means likes this ?
SELECT COUNT(*)
FROM yourTable
WHERE ....
You can make global function that you can use all the time as
public static int GetTableCount(string tablename, string connStr = null)
{
string stmt = string.Format("SELECT COUNT(*) FROM {0}", tablename);
if (String.IsNullOrEmpty(connStr))
connStr = ConnectionString;
int count = 0;
try
{
using (SqlConnection thisConnection = new SqlConnection(connStr))
{
using (SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
{
thisConnection.Open();
count = (int)cmdCount.ExecuteScalar();
}
}
return count;
}
catch (Exception ex)
{
VDBLogger.LogError(ex);
return 0;
}
}
This works for me
using (var context = new BloggingContext())
{
var blogs = context.Blogs.SqlQuery("SELECT * FROM dbo.Blogs").ToList();
}
For more information consult: https://learn.microsoft.com/es-es/ef/ef6/querying/raw-sql?redirectedfrom=MSDN
Use this its working
string strQuery = "SELECT * FROM staff WHERE usertype='lacturer'";
connect.Open();
SqlCommand cmd = new SqlCommand(strQuery, connect);
SqlDataAdapter OleDbDa = new SqlDataAdapter(cmd);
DataSet dsData = new DataSet();
OleDbDa.Fill(dsData);
connect.Close();
std.Text = dsData.Tables[0].Rows.Count.ToString();
I used this method in my own application to count the number of active users within the program. This can be easily manipulated for your own use.
con.open();
string ActiveUsers = "SELECT * FROM Devices WHERE Status='" + "Online" + "'";
SqlCommand cmd = new SqlCommand(ActiveUsers, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
con.Close();
Users.Text = ds.Tables[0].Rows.Count.ToString();

Categories

Resources