Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want convert this code into using a DataSet.
I don't have any idea how to retrieve data from a DataSet.
conn.Open();
string strquery = "select * from tblclientinfo where clientId=" +
txtid.Text; SqlCommand sqlcmd = new SqlCommand(strquery, conn);
SqlDataReader sqldreader = sqlcmd.ExecuteReader();
if (sqldreader.HasRows)
{
while (sqldreader.Read())
{
txtid.Text = sqldreader["clientId"].ToString();
txtname.Text = sqldreader["name"].ToString();
txtmobile.Text = sqldreader["mobile"].ToString();
txtcnic.Text = sqldreader["cnic"].ToString();
}
}
else
{
MessageBox.Show("Record for ID" + " " + txtid.Text + " " + "Not Found !");
}
sqldreader.Close();
conn.close();
Do you want something like this ?
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand.CommandText = "select * from tblclientinfo where clientId = #id";
da.SelectCommand.Parameters.AddWithValue("#id", txtid);
da.SelectCommand.Connection = conn;
DataSet ds = new DataSet();
da.Fill(ds);
foreach (DataRow row in ds.Tables[0].Rows)
{
txtid.Text = row["clientId"].ToString();
txtname.Text = row["name"].ToString();
...
}
The DataReader is the active part reading in the data from the database connection.
The DataSet is a container defined in a generic way so that it may contain any structure of data that tis read in by a DataReader.
You can use this approach:
// Assumes that conn is a valid SqlConnection object.
string strquery = "select * from tblclientinfo where clientId=" + txtid.Text;
SqlDataAdapter adapter = new SqlDataAdapter(strquery , conn);
DataSet resultSet = new DataSet();
resultSet.Fill(resultSet, "resultSet");
//now you can read data from DataTables contained in your dataset and do whatever with it
DataTable FirstTableOfDataSet = resultSet.Tables[0];
As your question asks about the difference, so here it goes:
DataReader is used in connected architecture. That means a connection remains open till you iterate through and fetch all records one by one. Only after fetching records when you write con.Close() it gets closed.
DataSet and DataAdapter are used in disconnected Architecture. That means they bring data and do not have a open connection for a long time. So in case if the database get changed after bringing data you won't have the updates, because it is cached.
Take an example:
An oil company is located at say Dubai(DataSource - Database), it needs to send oil to say USA(Application UI). What are the two ways?
A jet plane carries the oil to USA.- Disconnected. The jet plane is the DataAdapter and the container in which the oil is brought is dataset/datatable.
A pipeline runs through Dubai to USA. - Connected. The pipeline is the reader.
Awkward example. ;) Hope this make the difference little clear.
Related
This question already exists:
I have around 20000 key value pairs for a dictionary, how do I create without getting slow or memory problem C#? [closed]
Need to create a dictionary (not C# Dictionary) which have 20,000 words. what is the best way to store data and search data? I have key values 20,000 [duplicate]
Closed 1 year ago.
OleDbConnection connection;
OleDbCommand command;
string commandText = "SELECT pali,sinhala FROM [Sheet3$]";
string oledbConnectString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source=Book2.xlsx;" +
"Extended Properties=\"Excel 12.0;HDR=YES\";";
connection = new OleDbConnection(oledbConnectString);
command = new OleDbCommand(commandText, connection);
OleDbDataAdapter da = new OleDbDataAdapter(command);
connection.Close();
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
Excel sheet have 20 000 rows(UTF8 unicode). even my Lap 8gb ram i3 it takes like 8secs to load. Is their any way to store these data? I want to create a Dictionary(not csharp dictionary).
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I wanted to know how I can add data returned from a stored procedure directly into a dataGridview.
I'm creating an attendance system in C# and I was sending the Class_Id and Sub_Id back to the stored procedure via combobox so that I can I can only see the students that are present in a certain class for a certain subject but I don't know how to add the returned results directly into a dataGridView
Attendance Screenshot.
In the screenshot, I am sending back the Class_Id and Sub_Id so that It only shows me the students that have those id in the stored procedure.
I executed the query in the stored procedure and It showed me the students that had the Class_id and Sub_Id I specified.
Stored procedure
Here is the screenshot for the code
Code Image
Use an Adapter to fill the DataTable and add that DataTable to the DataSource property of the DataGridView:
DataTable result = new DataTable();
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter("StoredProcedureName", conn);
adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
adapter.SelectCommand.Parameters.Add("#subid",SqlDbType.Int).Value= comboBox1.SelectedValue;
adapter.SelectedCommand.Parameters.Add("#classid",SqlDbType.Int).Value=comboBox1.SelectedValue;
adapter.Fill(result);
}
dataGridView1.DataSource = result;
If your #subid and #classid is typeof int, I think you need to convert your ComboBox value to int.
You can try with Convert.ToInt32(comboBox1.Value) or even better int.TryParse(comboBox1.Value, out result)
may be this can be helpful to you.. you can replace my query with your stored procedure
Dim con As SqlConnection = New SqlConnection("server = ADITYA\CBOWR; database = adi; integrated security = true;")
Dim cmd As SqlCommand = New SqlCommand()
Dim query As String = "Select * from address"
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.CommandText = query
Dim sda As SqlDataAdapter = New SqlDataAdapter(query, con)
Dim ds As DataSet = New DataSet()
con.Open()
sda.Fill(ds)
GridView1.DataSource = ds
GridView1.DataBind()
con.Close()
I'm currently trying to use C# to read through an SQL DB. To do so, I use OleDB with a select statement. This goes into a dataset, which then populates a data adapter. I then iterate through each row and calculate stuff.
First of all, I feel like there's a better/more efficient way of doing this because I NEVER actually write back to the SQL DB. I just calculate based on what I'm selecting.
Anyways, past a certain point I get out of memory errors and/or an error from Ssms.exe saying "a new guard page for the stack cannot be created."
From the other questions I've seen, I need to use DataReader but I can't seem to get it to work the same way as the data adapter (which I suppose isn't that surprising).
The code I have now:
OleDbConnection myConn = new OleDbConnection(#"SQLDB connection string here");
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = <selectstatement here>
cmd.Connection = myConn;
cmd.CommandTimeout = 0;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
myConn.Close();
foreach (DataTable table in ds.Tables)
{
foreach (DataRow dr in table.Rows)
{
//do stuff
I guess my question is twofold, like I said above. One would DataReader solve my problem and allow me to iterate through the data, and two how do I adapt the first code snippet above to support that?
Also, since I've seen it elsewhere, I'm using x64 on the application.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have this code
public static DataSet tipopromocion(string id_edificio,string date_from, string date_to)
{
DataSet tipo = new DataSet();
MySqlConnection con = new MySqlConnection(connectionstring);
string tipo_promo = "select pr.tipo_promocion from promocion_edificio pe inner join inventario i on i.id_edificio = pe.id_edificio inner join promocion pr on pe.id_promocion=pr.id_promocion where i.id_edificio = '" + id_edificio + "' and i.fecha between '" + date_from + "' and Date_Sub('" + date_to + "',interval 1 Day) and i.fecha between pe.inicio_promo AND pe.fin_promo and date(now()) between pe.inicio_alojamiento and pe.fin_alojamiento AND ( FIND_IN_SET('A',pe.tipo)) group by pe.id_promocion order by pr.valor_promocion desc";
MySqlCommand cmd13 = new MySqlCommand(tipo_promo, con);
MySqlDataAdapter da13 = new MySqlDataAdapter(cmd13);
da13.Fill(tipo);
return tipo;
}
tipo_promonic
-------------
porcentaje
porcentaje
fixed
discount
porcentaje
discount
discount
fixed
fixed
porcentaje
porcentaje
the above result like above table table ok now i am trying to check in "tipo_promonic" column contains some rows so i am checking if "tipo_promonic" column contains porcentaje,fixed,discount then go to some function else it goto another function ok but in "tipo_promonic" column contains many duplicate values so how to check the condition. please help me out from this problem.
Try Re-framing your SQL query using DISTINCT keyword to avoid Duplicate record
string tipo_promo = "select DISTINCT pr.tipo_promocion from promocion_edificio pe inner ..."
Try using DataReader
MySqlConnection con = new MySqlConnection(connectionstring);
string tipo_promo = "select DISTINCT pr.tipo_promocion from promocion_edificio pe inner.."
MySqlCommand cmd13 = new MySqlCommand(tipo_promo, con);
DataReader dr = cmd13.ExecuteReader();
while(dr.Read())
{
if(dr[0].ToString() == "YourOption")
{//Do this;}
}
This is for a data table. You can make out for DataAdapter or Dataset according to your need. This is basically a loop which checks each row for a value of a particular column.
foreach (DataRow dr in dataTable.Rows)
{
if (dr["typo_promonic"].Equals("porcentaje"))
{
//your code here.
}
else if (dr["tipo_promonic"].Equals("discount"))
{
//your code here.
}
else
{
//your code here.
}
}
You can add more else...if as per your options. Whatever you want to do, you can do in those code blocks.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
How to query on table's view in .Net C# web application ?
for example, here [View_App_Academic] is my table view. My code is listed below. under db scheme, I am not able to see the view due to my user privilege.
string strquery = "select * from [dbo].[View_App_Academic] where recruitment_id=" +
RecruitDropDownList.Text + " and ref_no='" + RefDropDownList.Text + "'";
SqlCommand objCMD = new SqlCommand(strquery, conn);
Use parameterized query always.
Remove [dbo] from your query, you don't need to add [dbo] because it is default database schema.
Change your code to this.
string strquery = "select * from View_App_Academic where recruitment_id=#recruitment_id and ref_no=#ref_no";
SqlCommand objCMD = new SqlCommand(strquery, conn);
objCMD.Parameters.AddWithValue("#recruitment_id", RecruitDropDownList.Text);
objCMD.Parameters.AddWithValue("#ref_no",RefDropDownList.Text);
SqlDataAdapter myAdapter = new SqlDataAdapter();
myAdapter.SelectCommand = objCMD;
DataSet myDataSet = new DataSet();
myAdapter.Fill(myDataSet);
Hope it helps.