How to pass data, select for an array - c#

How to save the select data below into an array.
SqlConnection conConexao1 = clsdb.AbreBanco();
SqlCommand cmd1 = new SqlCommand("select id, tamplete1, tamplete2 from usuarios ", conConexao1);
SqlDataReader dr1 = cmd1.ExecuteReader();
if (dr1.HasRows == true)
{
if (dr1.Read())
{
id = int.Parse(dr1[0].ToString());
templete1 = (dr1[1].ToString());
templete2 = (dr1[2].ToString());
}
}
I have already tried using foreach, but always passes the last table data.

As a collection, List provide better flexibility than array.
The collection should be created outside the loop and the element should be added inside the loop.
List<Usuarios> list = new List<Usuarios>();
using (SqlConnection conConexao1 = clsdb.AbreBanco())
using (SqlCommand cmd1 = new SqlCommand(
"select id, tamplete1, tamplete2 from usuarios ", conConexao1))
using (SqlDataReader dr1 = cmd1.ExecuteReader())
{
while (dr1.Read())
{
list.Add(new Usuarios
{
Id = dr1.GetInt32(0),
Templete1 = dr1[1].ToString(),
Templete2 = dr1[2].ToString()
});
}
}
The class to imitate your data structure
public class Usuarios
{
public int Id { get; set; }
public string Templete1 { get; set; }
public string Templete2 { get; set; }
}
if for some reason, you have to use an array as collection
Usuarios[] array = list.ToArray();

Related

How to show all data from c#

I'm kind a new on c#. I have a problem with to store the className to list since i need to display all the class that teacher taught. On result, it turns out just the last class teacher taught. I did use join table between teacher and classes.
Model
public class Teacher
{
public int teacherId { get; set; }
public string teacherfName { get; set; }
public string teacherlName { get; set; }
public string className { get; set; }
public int classId { get; set; }
}
Controller
public Teacher FindTeacher(int id)
{
Teacher newTeacher = new Teacher();
MySqlConnection Conn = school.AccessDatabase();
Conn.Open();
MySqlCommand cmd = Conn.CreateCommand();
//SQL QUERY
cmd.CommandText = "Select * from teachers left join classes on teachers.teacherid=classes.teacherid where teachers.teacherid = " + id;
//Gather Result Set of Query into a variable
MySqlDataReader ResultSet = cmd.ExecuteReader();
while (ResultSet.Read())
{
int teacherId = (int)ResultSet["teacherId"];
string teacherfName=ResultSet["teacherfname"].ToString();
string teacherlName=ResultSet["teacherlname"].ToString();
newTeacher.teacherId = teacherId;
newTeacher.teacherFName = teacherFName;
newTeacher.teacherLName = teacherLName;
newTeacher.className = className;
newTeacher.classId = (int)ResultSet["classid"];
}
return newTeacher;
}
Your only returning one teacher if you want all the teachers your code should be:
public IEnumerable<Teacher> FindTeacher(int id)
{
//Lise here
List<Teacher> teachers = new List<Teacher>();
//note the using
using MySqlConnection Conn = school.AccessDatabase();
Conn.Open();
//note the using
using MySqlCommand cmd = Conn.CreateCommand();
//SQL QUERY
cmd.CommandText = "Select * from teachers left join classes on teachers.teacherid=classes.teacherid where teachers.teacherid = " + id;
//Gather Result Set of Query into a variable
MySqlDataReader ResultSet = cmd.ExecuteReader();
while (ResultSet.Read())
{
//new teacher in the loop
Teacher newTeacher = new Teacher();
int teacherId = (int)ResultSet["teacherId"];
string teacherfName=ResultSet["teacherfname"].ToString();
string teacherlName=ResultSet["teacherlname"].ToString();
newTeacher.teacherId = teacherId;
newTeacher.teacherFName = teacherFName;
newTeacher.teacherLName = teacherLName;
newTeacher.className = className;
newTeacher.classId = (int)ResultSet["classid"];
//add to the collection
teachers.Add(newTeacher);
}
//return the collection
return teachers;
}
If also added using statements. These are important to prevent memory leaks
Modify Teacher Class to be able to carry List of TeacherClass that correspond to one teacher:
Define New Class TeacherClass to Carry a TeacherClass Data
public class TeacherClass
{
public string Name { get; set; }
public int Id { get; set; }
}
Modify Teacher Class To have a List Of TeacherClass
public class Teacher
{
public int teacherId { get; set; }
public string teacherfName { get; set; }
public string teacherlName { get; set; }
public List<TeacherClass> classes { get; set; } = new List<TeacherClass>();
}
Then get your function to set this TeacherClass List in a loop:
public Teacher FindTeacher(int id)
{
Teacher newTeacher = new Teacher();
//note the using
using MySqlConnection Conn = school.AccessDatabase();
Conn.Open();
//note the using
using MySqlCommand cmd = Conn.CreateCommand();
//SQL QUERY
cmd.CommandText = "Select * from teachers left join classes on teachers.teacherid=classes.teacherid where teachers.teacherid = " + id;
//Gather Result Set of Query into a variable
MySqlDataReader ResultSet = cmd.ExecuteReader();
// Check if any rows retrieved
if (reader.HasRows)
{
// Iterate Over Rows
while (ResultSet.Read())
{
// Set Teacher Data Just Once
if(newTeacher.teacherId == 0){
newTeacher.teacherId = (int)ResultSet["teacherId"];;
newTeacher.teacherFName = ResultSet["teacherfname"].ToString();
newTeacher.teacherLName = ResultSet["teacherlname"].ToString();
}
// Add new TeacherClass data for this teacher
newTeacher.classes.Add(
new TeacherClass(){
Name = className, // className Check this variable as it is not declared
Id = (int)ResultSet["classid"]
});
}
}
return newTeacher;
}

How to get many field on the Query of webservice

I am making a web service get data from sql server. I need to get many fields from the sql server, but I can only get one field, which is the Currancy Name
namespace WebApplication2
{
public class DataHelper
{
public static string GetCurrency(string currencyCode)
{
string currencyName = "";
SqlConnection con = new SqlConnection(#"Data Source=WEB3\SHAREPOINT;Initial Catalog=WSS_Search_WEB3;Integrated Security=True");
SqlCommand cmd = new SqlCommand("select PO_NUMBER,PO_STATUS from View_1 where PO_HEADER_ID ='" + currencyCode.ToUpper() + "'", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
currencyName = dr["PO_NUMBER"].ToString();
}
dr.Close();
con.Close();
return currencyName;
}
}
}
I need to get the PO_Number & PO Status from the Query
As I understand you need to return not only PO_NUMBER, but also PO_STATUS, and as I understand you want to return both values.
I suggest you make model that represent what you want to return.
So for that we make a model class call it for instance POModel:
public class POModel
{
public string currencyName { get; set; } // PO_Number
public string statusName { get; set; } // PO_Status
}
Than fetch the values from SQL as you did and return object in stead of string.
Here would you final code looks like, of course naming and all the stuff you can change the way if fits best:
public class DataHelper
{
public static POModel GetCurrency(string currencyCode)
{
//string currencyName = "";
var poModel = new POModel();
SqlConnection con = new SqlConnection(#"Data Source=WEB3\SHAREPOINT;Initial Catalog=WSS_Search_WEB3;Integrated Security=True");
SqlCommand cmd = new SqlCommand("select PO_NUMBER,PO_STATUS from View_1 where PO_HEADER_ID ='" + currencyCode.ToUpper() + "'", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
poModel.currencyName = dr["PO_NUMBER"].ToString();
poModel.statusName = dr["PO_STATUS"].ToString();
}
dr.Close();
con.Close();
//return currencyName;
return poModel;
}
}
public class POModel
{
public string currencyName { get; set; }
public string statusName { get; set; }
}
One option is to return an array that contains the two values. Notice string[]:
public static string[] GetCurrency(string currencyCode)
Similar to how you declared string currencyName = "";, instead make an array variable:
string[] poData = new string[2];
Since this looks like it should return a single row, I would not loop. Just do a Read():
dr.Read();
poData[0] = dr["PO_NUMBER"].ToString(); //poData[] will have to be declared in your method
poData[1] = dr["PO_STATUS"].ToString();
....
return poData;

How to fetch Record in a faster manner from SQLDataReader In C#

we have a stored procedure , which results data as below.
testCol1 testCol2 testCol3 testCol4 testCol5
124 1234 4543 4532 5564
123 1235 4546 4537 5565
it has 190,000 records.
I am trying to fetch data in List<TestData> type and then pass it to third party.
below is the code:
public class TestData
{
public int testCol1 { get; set; }
public int testCol2 { get; set; }
public string testCol3 { get; set; }
public double? testCol4 { get; set; }
public int testCol5 { get; set; }
}
var inputs = new List<TestData>();
using (SqlConnection con = new SqlConnection(fitchConnectionString))
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "dbo.ReadAll_ForTest";
cmd.CommandTimeout = 0;
con.Open();
using (SqlDataReader dr = new SqlDataReader(cmd.ExecuteReader()))
{
while (dr.Read())
{
inputs.Add(new TestData()
{
testCol1 = (int)dr["testCol1"];
testCol2 = (int)dr["testCol2"];
testCol3 =(string)dr["testCol3"];
testCol4 = (double)dr["testCol4"];
testCol5 = (int)dr["testCol5"];
});
}
}
}
//pass to third party
var output = thirdparty.Convert(inputs).ToArray();
its working fine , however is taking lots of time to fetch the data.
is there is a way we can fetch data in faster manner?
One way is to specify types explicitly, so that the framework doesn't have to figure out what you mean. Get the ordinals (indices) in advance, and extract the exact type from the column:
using (var dr = cmd.ExecuteReader())
{
var testCol1Idx = dr.GetOrdinal("testCol1");
var testCol2Idx = dr.GetOrdinal("testCol2");
var testCol3Idx = dr.GetOrdinal("testCol3");
var testCol4Idx = dr.GetOrdinal("testCol4");
var testCol5Idx = dr.GetOrdinal("testCol5");
while (dr.Read())
{
inputs.Add(new TestData()
{
testCol1 = dr.GetInt32(testCol1Idx);
testCol2 = dr.GetInt32(testCol2Idx);
testCol3 = dr.GetString(testCol3Idx);
testCol4 = dr.GetDouble(testCol4Idx);
testCol5 = dr.GetInt32(testCol5Idx);
});
}
}
Other than that, 100K+ are a lot of records. Do you really need all of them? Try to work with a subset of the data, or aggregate data before using them.

How to read and write objects into SQL Server database?

My first table is Clinics with columns:
ClinicId, ClinicName, ClinicShortName
My second table is Employees with columns:
EmployeeId, EmployeeName, ClinicId, OnJob
I also have a view v_employees defined as:
SELECT
Employees.EmployeeId, Employees.EmployeeName,
Clinics.ClinicShortName,
Employees.OnJob
FROM
Clinics
INNER JOIN
Employees ON Clinics.ClinicId = Employees.ClinicId
And my C# code is:
class Employee
{
public int EmployeeId { get; set; }
public string EmpolyeeName { get; set; }
public int ClinicId { get; set; }
public bool OnJob { get; set; }
}
class Clinic
{
public int ClinicId { get; set; }
public string ClinicName { get; set; }
public string ClinicShortName { get; set; }
}
List<Employee> employeeList = new List<Employee>();
private void InitEmployees()
{
SqlConnection con = new SqlConnection(......);
SqlCommand cmd = new SqlCommand("select * from v_employees", con );
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Employee employee = new Employee()
{
EmployeeId = Convert.ToInt32(dr["EmployeeId"]),
EmpolyeeName = dr["EmployeeName"].ToString(),
// how to use ClinicShortName field in this position?
// Because I want the data to be displayed into DataGridView control.
OnJob = Convert.ToBoolean(dr["OnJob"])
};
employeeList.Add(employee);
}
dr.Close();
con.Close();
dataGridView1.DataSource = employeeList;
}
How could I import objects into SQL Server?
Should I use the List<T> method?
You have to add a field of ClinicShortName into employee class but why not use sqladapter? it generates columns according to the data returned
SqlConnection con = new SqlConnection(......);
SqlCommand cmd = new SqlCommand("select * from v_employees", con );
con.Open();
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(table);
dr.Close();
con.Close();
dataGridView1.DataSource = table;

Display Data to spesific column Grid control devexpress using oracle data reader

I have tried display data from spesific column ListView in C# and it was successfull. But I couldn't display it into spesific column in GridControl DevExpress.
This my code in ListView:
OracleCommand cmd = new OracleCommand();
OracleDataReader dr;
cmd.CommandText = #"SELECT * FROM PERMOHONANDETAIL WHERE PERMOHONANFK = '" + buka.txtID.Text + "'";
cmd.Connection = koneksi_manual.con;
dr = cmd.ExecuteReader();
while (dr.Read())
{
ListViewItem list = new ListViewItem(dr["PEKERJAAN"].ToString());
list.SubItems.Add(dr["KODEPEKERJAAN"].ToString());
list.SubItems.Add(dr["PEKERJAAN"].ToString());
list.SubItems.Add(dr["JOBFORM"].ToString());
list.SubItems.Add(dr["QTYORDER"].ToString());
list.SubItems.Add(dr["TARGETPERHARI"].ToString());
list.SubItems.Add(Convert.ToDateTime(dr["TANGGALSTART"]).ToString("dd/MM/yyyy"));
list.SubItems.Add(Convert.ToDateTime(dr["TANGGALEND"]).ToString("dd/MM/yyyy"));
list.SubItems.Add(dr["DURASIHARI"].ToString());
list.SubItems.Add(dr["NOTES"].ToString());
buka.listView1.Items.Add(list);
}
dr.Close();
buka.Focus();
buka.ShowDialog();
How can I do it into spesific column GridControl in DevExpress?
How can I solve this??
You can create a class for your rows and use the List<YourClass> as DataSource for your GridControl.
For example, you can create this class:
public class GridControlItem
{
public string KODEPEKERJAAN { get; set; }
public string PEKERJAAN { get; set; }
public string JOBFORM { get; set; }
public string QTYORDER { get; set; }
public string TARGETPERHARI { get; set; }
public string TANGGALSTART { get; set; }
public string TANGGALEND { get; set; }
public string DURASIHARI { get; set; }
public string NOTES { get; set; }
}
And use it in your GridControl as follows:
OracleCommand cmd = new OracleCommand();
OracleDataReader dr;
cmd.CommandText = #"SELECT * FROM PERMOHONANDETAIL WHERE PERMOHONANFK = '" + buka.txtID.Text + "'";
cmd.Connection = koneksi_manual.con;
dr = cmd.ExecuteReader();
var list = new List<GridControlItem>();
while (dr.Read())
{
var item = new GridControlItem();
item.KODEPEKERJAAN = dr["KODEPEKERJAAN"].ToString();
item.PEKERJAAN = dr["PEKERJAAN"].ToString();
item.JOBFORM = dr["JOBFORM"].ToString();
item.QTYORDER = dr["QTYORDER"].ToString();
item.TARGETPERHARI = dr["TARGETPERHARI"].ToString();
item.TANGGALSTART = Convert.ToDateTime(dr["TANGGALSTART"]).ToString("dd/MM/yyyy");
item.TANGGALEND = Convert.ToDateTime(dr["TANGGALEND"]).ToString("dd/MM/yyyy");
item.DURASIHARI = dr["DURASIHARI"].ToString();
item.NOTES = dr["NOTES"].ToString();
list.Add(item)
}
dr.Close();
gridControl1.DataSource = list;

Categories