Speedup ExecuteReader in C# - c#

I'm using a C# SqlDataReader in many loops. Unfortunately I can't read the whole table and store the data in a list. So I have to create a SqlDataReader again and again. Once the SqlDataReader is created, its very fast. But the creation of the SqlDataReader via ExecuteReader takes too much time.
Is there any possibility to improve the creation time of the SqlDataReader?
I'm using .NET 4.5.1 and SQL Server 2008.
string sql = "select CURRENT_TIMESTAMP";
var connection = Connections.Get();
SqlCommand sqlCommand = new SqlCommand(sql, connection);
sqlCommand.CommandTimeout = 0;
var reader = sqlCommand.ExecuteReader(CommandBehavior.Default);
Thanks
Michael

string conString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString();
SqlConnection conn = new SqlConnection(conString);
conn.Open();
SqlCommand cmd = new SqlCommand("select TOP 50000 * from users", conn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
please use DataTable and SqlDataAdapter to read the data
Instead of using ExecuteReader

Related

Adding integer parameter to stored procedure in ASP.NET C#

While trying to pass an integer parameter #id to a stored procedure, I get an error da.Fill(ds):
Additional information: Conversion failed when converting the varchar value '#id' to data type int.
I have made sure that integer value is passed and stored procedure contain the correct datatype. What other possibilities are there to rectify this error?
SqlConnection conn = new SqlConnection(cs);
conn.Open();
SqlCommand cmd1 = new SqlCommand("asp_GetTrainingDetail", conn);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#id", id);
SqlDataAdapter da = new SqlDataAdapter(cmd1);
DataSet ds = new DataSet();
da.Fill(ds);
If you know better, do not use AddWithValue() ... it has to "guess" what datatype you have in your DB based on what you put into the command. It is errorprone and causes unneeded conversions to take place.
Also: use using(..) around disposables, especially when using Database-access as it will close your connections even if exceptions arise - not using using might let some connection stay unclosed.
DataSet ds = new DataSet ();
using (var conn = new SqlConnection (cs))
{
using (var cmd1 = new SqlCommand ("asp_GetTrainingDetail", conn))
{
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.Add("#id", System.Data.SqlDbType.BigInt).Value = id;
using (var da = new SqlDataAdapter (cmd1))
{
da.Fill (ds);
}
}
}
Read the link in do not use AddWithValue() for more background infos.
Try this...
SqlConnection conn = new SqlConnection(cs);
conn.Open(); SqlCommand cmd1 = new
SqlCommand("asp_GetTrainingDetail", conn);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#id", Int.Parse(id));
SqlDataAdapter da = new SqlDataAdapter(cmd1);
DataSet ds = new DataSet();
da.Fill(ds);

Storing multiple values from an SQL select statement

I have an SQL select query that will return multiple values, but I cannot find a way to store/access them. I am using Visual Studio 2015 and an Access database.
Below is my most recent attempt using a data table/grid view.
string now = DateTime.Today.ToString("dd/MM/yyyy");
//Establish and open new database connection.
OleDbConnection con = new OleDbConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["MyDatabase32BITConnectionString"].ToString();
con.Open();
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter adapter = new OleDbDataAdapter();
DataTable dt = new DataTable();
cmd.CommandText = String.Format ("select Rating from [RATINGS] where Today_Date like #now and Name like #name");
cmd.Parameters.AddWithValue("#now", now);
cmd.Parameters.AddWithValue("#name", name);
cmd.Connection = con;
adapter.SelectCommand = cmd;
adapter.Fill(dt);
con.Close();
testGridView.DataSource = dt;
name is a variable passed into the method. I don't necessarily need it stored in a data table, i just need to be able to access the results individually to average them (array?).
Any advice would be much appreciated

How use WHERE in SqlDataAdapter in C#

How use WHERE in SqlDataAdapter in C#?
I want get name in a textbox and use that at query but it wont work .
SqlConnection sqlconnection = new SqlConnection("Server=Behnam\\Accounting;Initial Catalog=Accounting;Integrated Security=TRUE");
DataTable dt = new DataTable();
string _search_name = txt_search.Text;
SqlDataAdapter SDA = new SqlDataAdapter("SELECT dbo.tbl_user.field1,dbo.tbl_user.field2 FROM tbl_user WHERE dbo.tbl_user.name=_search_name ", sqlconnection);
SDA.Fill(dt);
dataGridView1.DataSource = dt;
Prepare the command text and use a parameter for the value of your search.
Then use that command text to initialize a new SqlCommand. Fill the parameter value with AddWithValue and pass the SqlCommand to the constructor of the SqlDataAdapter.
string cmdText = "SELECT dbo.tbl_user.field1,dbo.tbl_user.field2 " +
"FROM tbl_user WHERE dbo.tbl_user.name=#search_name"
SqlCommand cmd = new SqlCommand(cmdText, sqlconnection);
cmd.Parameters.AddWithValue("#search_name", _search_name);
SqlDataAdapter SDA = new SqlDataAdapter(cmd);
The SqlDataAdapter will store your command as the SelectCommand property and will use the passed in SqlCommand to execute the query to retrieve the records from the database.
Keep in mind that AddWithValue is a shortcut with some drawbacks. For example it pass Always a string as a nvarchar parameter with size equal to the actual lenght of the variable. This effectively reduces the performance of the Sql Server Optimizer.
This is a very enlightening article on the issue
So, you were pretty close, you just needed to define a parameter inside the query and then add that parameter. However, in the following code block I've also conveniently recommended a more appropriate approach to using the classes needed to get the data (pun intended). The using statement here ensures that the objects get disposed of properly after you are done using them (man I just can't stop with the puns!)
using (SqlConnection c = new SqlConnection(connString))
{
c.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(
"SELECT dbo.tbl_user.field1, dbo.tbl_user.field2 FROM tbl_user " +
"WHERE dbo.tbl_user.name= #name", c))
{
sda.SelectCommand.Parameters.AddWithValue("#name", txt_search.Text);
DataTable dt = new DataTable();
sda.Fill(dt);
}
}
Try this.
you were using the string directly in the query which will go undetected.
SqlConnection sqlconnection = new SqlConnection("Server=Behnam\\Accounting;
Initial Catalog=Accounting;Integrated Security=TRUE");
DataTable dt = new DataTable();
SqlDataAdapter SDA = new SqlDataAdapter("SELECT dbo.tbl_user.field1,dbo.tbl_user.field2 FROM tbl_user WHERE dbo.tbl_user.name=#searchName" , sqlconnection);
SDA.SelectCommand.Parameters.AddWithValue("#searchName", txt_search.Text);
SDA.Fill(dt);
dataGridView1.DataSource = dt;

display individual columns from sql result in asp.net c#

I'm coding a simple application using c# asp.net. I'm getting the averages of columns. How can I get the individual values from the result and display it in a new label (label1, label2, label3....)?
I tried ExecuteScalar().ToString(); but it returns only the first column.
Below is my code:
SqlConnection con;
con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\STATDB.MDF;Integrated Security=True;User Instance=True");
SqlCommand com = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
string result = "SELECT AVG(p_tan) AS p_tang, AVG(e_tan) AS e_tang, AVG(p_rel) AS p_reli FROM statistics";
SqlCommand showresult = new SqlCommand(result, con);
con.Open();
Label1.Text = showresult.ExecuteScalar().ToString();
//Label2.Text = p_tang
//Label3.Text = e_tang
//Label4.Text = p_reli
con.Close();
Any help will be appreciated.
Use showresult.ExecuteReader() and then iterate over the row to get the values
SqlDataReader reader=showresult.ExecuteReader();
while (reader.Read())
{
Label1.Text= reader["p_tang"].ToString().Trim();
Label2.Text= reader["e_tang"].ToString().Trim();
Label3.Text= reader["p_reli"].ToString().Trim();
}
ExecuteScalar will only pull one value. You will need do either use a DataReader or DataAdapter to get multiple values from the database.

Prepared Statements in SQL-Server through C#

i found using of prepared statements in PHP by mysqli_stmt_prepare() Function.
what is like it in C# for SQL-Server?
i found this code example(using parameterize command). is this what i am looking for?
SqlConnection conn = new SqlConnection();
SqlCommand com = new SqlCommand();
SqlDataAdapter dap = new SqlDataAdapter();
DataTable tbl = new DataTable();
SqlParameter param = new SqlParameter();
conn.ConnectionString = #"Data Source=...";
com.Connection = conn;
com.CommandText = "select * from tbl1 where id<#id";
com.Parameters.AddWithValue("#id",4);
com.CommandType = CommandType.Text;
dap.SelectCommand = com;
conn.Open();
dap.Fill(tbl);
conn.Close();
dataGridView1.DataSource = tbl;
if NO, then what?
if YES, tell me how to using character '?' instead of writing #id in command text.
thanks
SQL Server (at least, via SqlClient) uses named parameters. That code will indeed execute a parameterised query, but a few notes:
it hasn't been formally "prepared" (see .Prepare()), but you pretty much never need to anyway
several of those objects are IDisposable; you should have usings for them
DataTable (and adapter, etc) will work, but is in decline (with mapped classes being preferred, IMO)
seeing a DataGridView and a SqlCommand in the same method probably means your UI code is too close to the data access code; I would push the data-access stuff down a level, personally
For example:
DataTable tbl = new DataTable();
using(var conn = new SqlConnection(#"Data Source=..."))
using(var com = conn.CreateCommand())
{
com.CommandText = "select * from tbl1 where id<#id";
com.Parameters.AddWithValue("#id",4);
com.CommandType = CommandType.Text;
SqlDataAdapter dap = new SqlDataAdapter();
dap.SelectCommand = com;
conn.Open();
dap.Fill(tbl);
conn.Close();
}
return tbl;
(and bind it to the DataGridView back at the UI)
Of course, if the parameter value is always 4 you could code that into the TSQL directly.
Yes, but it is no way to use '?' mark.

Categories

Resources