I am using Windows application c#. When I bind the data table to Datagridview it gets slow and I am getting a SQL connection timeout error.
At the same time my data table has bulk records. How can I solve this problem?
Code:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
con.StatisticsEnabled = true;
con.Open();
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand("select * from Stktrn_table", con);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
GridDisplay.ItemsSource = dt.DefaultView;
}
SqlCommand cmdVoid = new SqlCommand("select party_no, smas_rtno,convert(numeric(18,2),SUM(smas_NetAmount)) as Amount from salmas_table where ctr_no=#tCounter and Smas_Cancel<>1 and smas_rtno<>0 and Smas_billdate=#tDate group by smas_rtno, party_no", con);
cmdVoid.Parameters.AddWithValue("#tDate", dpBillDate.SelectedDate.Value);
cmdVoid.Parameters.AddWithValue("#tCounter", tCounterNoNew);
SqlDataAdapter adpVoid = new SqlDataAdapter(cmdVoid);
adpVoid.Fill(dtVoid);
This line
SqlCommand cmd = new SqlCommand("select * from Stktrn_table", con);
Will be your problem. Do not select all rows from the database, limit it using TOP
SELECT TOP 100 Column1, Column2, Column3 FROM Stktrn_table
in general SELECT * is bad practice.
Or alternatively, implement paging so the rows are loaded on demand rather than upfront.
How does the query run within SQL Server management studio? This should be your initial indicator of how long the query will return from the database.
You could also use a stored procedure which may give you a performance benefit over a raw SQL query.
First thing You should not use like this Select * from table_name instead this you should use select column_1,column_2,column3,column_n i.e. select only columns which you needed.
Second thing always use classes(BLL and DLL) instead of coding directly for database at page load or any form.
Third always use try catch block.
Third thing whenever you create a object, you should dispose that in finally block of try catch.
for ex.
DataTable dt = null;
SqlDataAdapter da = null;
SqlConnection con = null;
try
{
con=new SqlConnection("Connection_Source");
con.Open();
da = new DataAdapter("select * from table_name",con);
dt=new DataTable();
da.Fill(dt);
dataGridViewObj.DataSource=dt;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if(con.State==ConnectionState.Open)
con.Close();
dt.Dispose();
if(dt!=null)
dt=null;
da.Dispose();
if(da!=null) da=null;
}
Related
I am trying to get the name of the employee from the database and fill it in the textbox for the respective employee id.
I tried this code but nothing is happening on the page. It just reloads and the textbox (name) is left blank only.
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-0FUUV7B\SQLEXPRESS;Initial Catalog=EmployeeDetails;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select * from ProfessionalDetails where EmpId='"+EmployeeId.Text+"'", con);
SqlDataReader da = cmd.ExecuteReader();
while (da.Read())
{
Name.Text = da.GetValue(1).ToString();
}
con.Close();
Better solution is to execute the sql statement through Parameterized value.
The details of that process is given below:
using (SqlConnection con = new SqlConnection(live_connectionString))
{
using (SqlCommand cmd = new SqlCommand("Query", con))
{
con.Open();
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#EmpId", employeeId);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
var ds = new DataSet();
da.Fill(ds);
string? name = ds.Tables[0].Rows[1]["Variable name"].ToString();
Name.Text =name;
};
}
}
As mentioned above in comments, you have lot of issues.
you should use using with the connection to dispose of them.
You should use parameterized queries to avoid SQL injection.
Put your code in try catch so that you can easily identify the root cause of the issue.
Define the connection string in config file three than defining in the c# code.
You don’t need to select all the columns. And please avoid select * in the query, instead just write your column name, as you want to select only one column here.
You can use ExecuteScalar, it’s used when you are expecting single value.
And first make sure that textbox has the expected value when you are calling this query.
As noted, use paramters, and BETTER use STRONG typed paramters.
And no need to use a dataset, this is a single table - so use a datatable.
thus:
string strSQL =
#"select * from ProfessionalDetails where EmpId= #ID";
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmd = new SqlCommand(strSQL, con))
{
con.Open();
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = EmployeeID.Text;
DataTable rstData = new DataTable();
rstData.Load(cmd.ExecuteReader());
if (rstData.Rows.Count > 0)
Name.Text = rstData.Rows[0]["Name"].ToString();
}
}
I want to return a list of data from database, I pass params to a stored procedure, it then returns results to a list
List<DataDetail> FetchData(GenRequest Request)
{
List<DataDetail> details = new List<DataDetail>();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
// con.Open();
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand("sp_Gen", con);
con.Open();
cmd.Parameters.AddWithValue("#ForcedATMAmt", ForcedATMAmt);
cmd.Parameters.AddWithValue("#OthersValue", OthersValue);
con.Close();
cmd.ExecuteReader();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
DataDetailobj = new DataDetail();
obj.AdditionalPremium = dr["AdditionalPremium"].ToString();
obj.ATMLimit = dr["ATMLimit"].ToString();
details.Add(obj);
}
}
return details
}
I tried the approach in the code above but when I hover over dr, the dr.HasRows is false. any way I can return the data to a list without DataRows?
Generally speaking, when working with a database connection your order of operations is:
Open the database connection
Run your queries/commands
Close the database connection
In your case, it should go something like this:
con.Open()
SqlCommand cmd = new SqlCommand("sp_Gen", con);
// add parameters
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
// run your code to get values from da
con.Close()
As a side note, I don't believe you need to call cmd.ExecuteReader(); yourself, but that SqlDataAdapter.Fill() will execute the command for you.
Here what I have done
I make a GridView and choose the data key name as id and in the basis of id I want to show the DetailsView. Here the CS code
using (SqlConnection con1 = new SqlConnection("Data Source= IA; initial catalog =aip; integrated Security=true;"))
{
con1.Open();
SqlCommand cmd = new SqlCommand("select * from Pm where user_id='" +(String)Session["uid"]+ "'", con1);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
con1.Close();
}
Then I make DetailsView method on SelectedIndexChanged:
But it is showing empty DetailsView in output on selecting 'Select' option
here is the code image
enter image description here
You have used the DataSet not DataTable. So you could either do this:
da.Fill(ds,"tbl");
GridView1.DataSource = ds.Tables[0];
Or use a DataTable instead:
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
Also you should always use parameterized queries to avoid SQL Injection. Something like this:
SqlCommand cmd = new SqlCommand("select * from Pm where user_id=#userId", con1);
cmd.Parameters.AddWithValue("#userId", (String)Session["uid"]);
Also have a look at this: Can we stop using AddWithValue() already?
you need to set DataTable instead of DataSet
GridView1.DataSource = ds.Tables["Pm"];
#PIYUSH Itspk please check query and replace
SqlCommand cmd = new SqlCommand("select * from Pm where user_id=" +Session["uid"].tostring()+ ", con1);
i think its help you if any other query please notify me
I am trying to make c# program, where I have to make a database report to be previewed at the datagridview. Data will be selected using the datetimepicker. I have written the code, it works but then if the date selected is of different months. No records appear
void FilterDBbtnClick(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection();
conn = new MySqlConnection(cs);
string data = "SELECT `Date`, `Process`, `Actual`, `Target` FROM `database` WHERE `Date` BETWEEN '"+this.fromDatePicker.Value+"' AND '"+this.toDatePicker.Value+"' order by `Date` desc";
MySqlCommand cmd = new MySqlCommand(data, conn);
cmd.Connection.Open();
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
DataSet dt = new DataSet();
sda.Fill(dt);
BindingSource bsource = new BindingSource();
bsource.DataSource = dt;
mondeDataTable.DataSource = dt.Tables[0];
sda.Update(dt);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
cmd.Connection.Close();
}
please help me check my code and tell me what might be wrong or missing.
Use profiler to check the query that hits the DB. I suspect it's a date formatting issue.
Maybe this question can help you with logging the queries that hit the database:
Hope this helps:
Select * from [Table] where StartDate between '06/13/2016' and '10/13/2016'
The above query fetches records between months 06 and 10. Make sure that string in the data variable is in the above format. Also the column type in the database is date.
Check and remove special characters, if any.
Mark this as answer if you find this useful.
Try this for your select query. I have changed one of your select variable because it ambiguous for the Date datatype.
void FilterDBbtnClick(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection();
conn = new MySqlConnection(cs);
//string data = "SELECT `Date`, `Process`, `Actual`, `Target` FROM `database` WHERE `Date` BETWEEN '"+this.fromDatePicker.Value+"' AND '"+this.toDatePicker.Value+"' order by `Date` desc";
//Changed query for getting data from DB according to the date
string data = "SELECT CreatedDate, Process, Actual, Target FROM database WHERE DATE_FORMAT(CreatedDate,'%Y-%m-%d') BETWEEN '"+this.fromDatePicker.Value.ToString("yyyy-MM-dd")+"' AND '"+this.toDatePicker.Value.ToString("yyyy-MM-dd")+"' order by CreatedDate desc";
MySqlCommand cmd = new MySqlCommand(data, conn);
cmd.Connection.Open();
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
DataSet dt = new DataSet();
sda.Fill(dt);
BindingSource bsource = new BindingSource();
bsource.DataSource = dt;
mondeDataTable.DataSource = dt.Tables[0];
sda.Update(dt);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
cmd.Connection.Close();
}
I'm new to MySQL and now i hava a project which must work with MYSQL. It's a win application and I use C# on Visual Studio 2010. I tried to write a simple stored procedure like this:
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `GetBank`()
BEGIN
SELECT * FROM BANKNAME;
END
And my C# code is here:
private void btnShow_Click(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection("SERVER=localhost;DATABASE=dowacodb;UID=root;PASSWORD=123456");
con.Open();
DataTable dt = new DataTable();
MySqlCommand cm = new MySqlCommand("GetBank", con);
cm.CommandType = CommandType.StoredProcedure;
MySqlDataAdapter da = new MySqlDataAdapter(cm);
da.Fill(dt);
con.Close();
dataGridView1.DataSource = dt;
}
My test is to show the data in datagridview when clicking the button. It shows fine on the first click but when I click again, the data in datagridview is gone. The next click will show the data again and repeatedly.
But this code will be perfect when not working with stored procedured
private void btnShow_Click(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection("SERVER=localhost;DATABASE=dowacodb;UID=root;PASSWORD=123456");
con.Open();
DataTable dt = new DataTable();
MySqlCommand cm = new MySqlCommand("Select * from bankname", con);
cm.CommandType = CommandType.Text;
MySqlDataAdapter da = new MySqlDataAdapter(cm);
da.Fill(dt);
con.Close();
dataGridView1.DataSource = dt;
}
So what's wrong with MySQL? Thanks in advance
The syntax to call your procedure in MySQL is
CALL GetBank()
so
MySqlCommand cm = new MySqlCommand("CALL GetBank()", con);
should do it. Which also removes the need to specify that your command cm is a stored procedure.
This problem is solved! Instead of using ordinary way to interact with MySQL: open a connection, create a command and use a data adapter to fill datatable, I use a MySQLHelper class and it works fine for me:
DataTable dt = MySqlHelper.ExecuteDataset("SERVER=localhost;DATABASE=dowacodb;UID=root;PASSWORD=123456", "call getbank()").Tables[0];
dataGridView1.DataSource = dt;
But now I wonder why this way works while the older way doesn't ?