I have two dropdownlists one of the country (worlddrdolist) and the another is of states (staatddl) and the button (NumOfUsrBtn) where if the user since click on it then the label will show the total sum of users depending on a country selected from (worlddrdolist) First whatever if the user select the state or not also if the user select the state then it will show the users depending of the country , the below code need update and fix some of part as i tried my best to fix but i coundnt, and i am receiving error message:
"Must declare the scalar variable "#cou"." also "Must declare the
scalar variable "#sta"."
protected void NumOfUsrBtn_Click(object sender, EventArgs e)
{
using (var conn = new SqlConnection(sc))
{
string UsrNumSQL = "SELECT COUNT (UsrID)FROM UserInfo WHERE 1=1 AND Country = #cou AND State=#sta";
using (var cmd = new SqlCommand(UsrNumSQL, conn))
{
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 10000;
cmd.Parameters.AddWithValue("#cou", worlddrdolist.SelectedValue);
cmd.Parameters.AddWithValue("#sta", staatddl.SelectedValue);
string condition = "";
if (worlddrdolist.SelectedValue != "")
{
condition += " and Country='" + worlddrdolist.SelectedValue + "'";
}
if (staatddl.SelectedValue != "")
{
condition += " and State='" + staatddl.SelectedValue + "'";
}
cmd.Connection.Open();
NumbOfUsersLbl.Text = cmd.ExecuteScalar().ToString();
}
}
}
This is not how parameterized queries works.
You need add your parameter value as a parameter in your command, not an additional condition.
cmd.Parameters.AddwithValue("#cou", worlddrdolist.SelectedValue);
cmd.Parameters.AddwithValue("#sta", staatddl.SelectedValue);
But I strongly suspect you just wanna add additional conditions with AND... at first place, you don't need to use parameter in your command at all. Looks like your conditions is not known at compile time, instead you wanna build them in runtime.
In such a case, just delete unnecessary parts in your query since you wanna add them based on your condition like;
string UsrNumSQL = "SELECT COUNT (UsrID)FROM UserInfo WHERE 1=1";
...
...
if (worlddrdolist.SelectedValue != "")
{
condition += " and Country='" + worlddrdolist.SelectedValue + "'";
}
if (staatddl.SelectedValue != "")
{
condition += " and State='" + staatddl.SelectedValue + "'";
}
cmd.Connection.Open();
NumbOfUsersLbl.Text = cmd.ExecuteScalar().ToString();
Related
I am trying to write a method which is supposed to retrieve multiple rows from a table in a database and use those data to instantiate a number of objects. However, as far as i can tell the database only returns the first row. When i do this:
public static List<Event> getMultipleEvents(string[] eventNames)
{
List<Event> rtnList = new List<Event>();
string EventsToRetrieve = "";
foreach (var item in eventNames)
{
if (EventsToRetrieve != "")
{
EventsToRetrieve += " OR ";
}
EventsToRetrieve += "eventName = '";
EventsToRetrieve += item;
EventsToRetrieve += "' ";
}
// This is the string that the method constructs based on the input i am testing with
//"eventName = 'event six' OR eventName = ' event two' OR eventName = ' event one' OR eventName = ' event seven' "
using (SqlConnection sqlConnection = Globals.GetSqlConnection())
{
sqlConnection.Open();
using (SqlCommand sqlCommand = new SqlCommand("SELECT * FROM questions WHERE " + EventsToRetrieve + ";", sqlConnection))
{
using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
{
if (sqlDataReader != null)
{
while (sqlDataReader.Read())
{
Event newEvent = new Event("", DateTime.MinValue, DateTime.MinValue);
string startDateTimeStringFromDB = sqlDataReader["startDateDay"].ToString() + "-" + sqlDataReader["startDateMonth"].ToString() + "-" + sqlDataReader["startDateYear"].ToString();
string endDateTimeStringFromDB = sqlDataReader["endDateDay"].ToString() + "-" + sqlDataReader["endDateMonth"].ToString() + "-" + sqlDataReader["endDateYear"].ToString();
newEvent.EventName = sqlDataReader["eventName"].ToString();
if (DateTime.TryParse(startDateTimeStringFromDB, out DateTime startDateTime))
{
newEvent.StartDate = startDateTime;
}
if (DateTime.TryParse(endDateTimeStringFromDB, out DateTime endDateTime))
{
newEvent.EndDate = endDateTime;
}
rtnList.Add(newEvent);
}
}
}
}
}
return rtnList;
}
Can anyone explain to me what i am doing wrong ? I Also tried wrapping the while loop in a do while loop as suggested here How to read multiple resultset from SqlDataReader? but it didn't change anything.
It doesn't seem to have any error in your code. however I believe that your query has errors.
First of all never ever use string concatenation when you are building your SQL Query. Instead use Parameterized Queries.
with the parameterized queries, it is even easier to debug your SQL statement since it does not include conditional string concatenations.
I have a program where I open a SqlConnection, load up a list of objects, modify a value on each object, then update the rows in the SQL Server database. Because the modification requires string parsing I wasn't able to do with with purely T-SQL.
Right now I am looping through the list of objects, and running a SQL update in each iteration. This seems inefficient and I'm wondering if there is a more efficient way to do it using LINQ
The list is called UsageRecords. The value I'm updating is MthlyConsumption.
Here is my code:
foreach (var item in UsageRecords)
{
string UpdateQuery = #"UPDATE tbl810CTImport
SET MthlyConsumption = " + item.MthlyConsumption +
"WHERE ID = " + item.Id;
SqlCommand update = new SqlCommand(UpdateQuery, sourceConnection);
update.ExecuteNonQuery();
}
Try this instead:
string UpdateQuery = #"UPDATE tbl810CTImport SET MthlyConsumption = #consumption WHERE ID = #itemId";
var update = new SqlCommand(UpdateQuery, sourceConnection);
update.Parameters.Add("#consumption", SqlDbType.Int); // Specify the correct types here
update.Parameters.Add("#itemId", SqlDbType.Int); // Specify the correct types here
foreach (var item in UsageRecords)
{
update.Parameters[0].Value = item.MthlyConsumption;
update.Parameters[1].Value = item.Id;
update.ExecuteNonQuery();
}
It should be faster because:
You don't have to create the command each time.
You don't create a new string each time (concatenation)
The query is not parsed at every iteration (Just changes the parameters values).
And it will cache the execution plan. (Thanks to #JohnCarpenter from the comment)
You can either use
SqlDataAdapter - See How to perform batch update in Sql through C# code
or what I have previously done was one of the following:
Tear down the ID's in question, and re-bulkinsert
or
Bulk Insert the ID + new value into a staging table, and update the table on SQL server:
update u
set u.MthlyConsumption = s.MthlyConsumption
from tbl810CTImport u
inner join staging s on
u.id = s.id
In a situation like this, where you can't write a single update statement to cover all your bases, it's a good idea to batch up your statements and run more than one at a time.
var commandSB = new StringBuilder();
int batchCount = 0;
using (var updateCommand = sourceConnection.CreateCommand())
{
foreach (var item in UsageRecords)
{
commandSB.AppendFormat(#"
UPDATE tbl810CTImport
SET MthlyConsumption = #MthlyConsumption{0}
WHERE ID = #ID{0}",
batchCount
);
updateCommand.Parameters.AddWithValue(
"#MthlyConsumption" + batchCount,
item.MthlyConsumption
);
updateCommand.Parameters.AddWithValue(
"#ID" + batchCount,
item.MthlyConsumption
);
if (batchCount == 500) {
updateCommand.CommandText = commandSB.ToString();
updateCommand.ExecuteNonQuery();
commandSB.Clear();
updateCommand.Parameters.Clear();
batchCount = 0;
}
else {
batchCount++;
}
}
if (batchCount != 0) {
updateCommand.ExecuteNonQuery();
}
}
It should be as simple as this . . .
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Server=YourServerName;Database=YourDataBaseName;Trusted_Connection=True");
try
{
//cmd new SqlCommand( "UPDATE Stocks
//SET Name = #Name, City = #cit Where FirstName = #fn and LastName = #add";
cmd = new SqlCommand("Update Stocks set Ask=#Ask, Bid=#Bid, PreviousClose=#PreviousClose, CurrentOpen=#CurrentOpen Where Name=#Name", con);
cmd.Parameters.AddWithValue("#Name", textBox1.Text);
cmd.Parameters.AddWithValue("#Ask", textBox2.Text);
cmd.Parameters.AddWithValue("#Bid", textBox3.Text);
cmd.Parameters.AddWithValue("#PreviousClose", textBox4.Text);
cmd.Parameters.AddWithValue("#CurrentOpen", textBox5.Text);
con.Open();
int a = cmd.ExecuteNonQuery();
if (a > 0)
{
MessageBox.Show("Data Updated");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
Change the code to suit your needs.
I have a form which displays selected datagridviewrow data in textboxes. I would like to edit and update the data from this form and update and save into the datatable when the user clicks update.
When I click update I get an error message:
There was an error parsing the query. [ Token line number = 1,Token line offset = 25,Token in error = ( ]
private void editBTN_Click(object sender, EventArgs e)
{
bool notEditable = true;
if (editBTN.Text == "Update")
{
UpdateDataBase();
editBTN.Text = "Edit";
deleteBTN.Visible = true;
notEditable = true;
}
else
{
deleteBTN.Visible = false;
editBTN.Text = "Update";
deleteBTN.Visible = false;
notEditable = false;
}
firstTxt.ReadOnly = notEditable;
surenameTxt.ReadOnly = notEditable;
address1Txt.ReadOnly = notEditable;
address2Txt.ReadOnly = notEditable;
countyTxt.ReadOnly = notEditable;
contactTxt.ReadOnly = notEditable;
emailTxt.ReadOnly = notEditable;
postTxt.ReadOnly = notEditable;
}
private void UpdateDataBase()
{
if (MessageBox.Show("Customer information will be updated. This change cannot be undone. Are you sure you want to continue? ", "Confirm Edit", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
string constring = #"Data Source=|DataDirectory|\LWADataBase.sdf";
string Query = "update customersTBL set ([First_Name] = '" + this.firstTxt.Text + "',surename= '" + this.surenameTxt.Text + "',[Address Line 1] = '" + this.address1Txt.Text + "',[Address Line 2] = '" + this.address2Txt.Text + "',County = '" + this.countyTxt.Text + "',[Post Code] = '" + this.postTxt.Text + "' , Email = '" + this.emailTxt.Text + "';,[Contact Number] = '" + this.contactTxt.Text + "');";
SqlCeConnection conDataBase = new SqlCeConnection(constring);
SqlCeCommand cmdDataBase = new SqlCeCommand(Query, conDataBase);
SqlCeDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
MessageBox.Show("Customer information has been updated", "Update Sucessful");
while (myReader.Read())
{
}
MessageBox.Show("Please exit the Customers window and re-open to update the table");
this.Close();
//displays a system error message if a problem is found
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
There are some problems in your code.
One is trivial and could be easily fixed (remove the semicolon before the [Contact Number], but there are other hidden problems that potentially are more serious.
First: Remember to always close and dispose the disposable objects
(connection and command in this case). The using statement ensure
that the object enclosed by the using block will be correctly closed
and disposed also in case of exceptions
Second: Use a parameterized query. This avoids Sql Injections and
parsing problems. If one or more of your input data contains a single
quote, the string concatenation used to build the sql command text
will resul in an invalid command
Third: An update command acts on all the records present in the table
if you don't add a WHERE condition. Usually the WHERE condition is
added to identify the only record that need to be updated and it is
the value of a field with UNIQUE index or the PRIMARY KEY of your
table. Of course you could update more than one record with a less
restrictive WHERE clause but this doesn't seem to be the case
Fourth: Use the ExecuteNonQuery instead of ExecuteReader for commands
that update/insert the database (well it works equally but why use a
method that should be reserved for other uses?)
private void UpdateDataBase(int customerID)
{
string constring = #"Data Source=|DataDirectory|\LWADataBase.sdf";
string Query = #"update customersTBL set [First_Name] = #fname,
surename = #sur, [Address Line 1] = #addr1,
[Address Line 2] = #addr2, County = #county,
[Post Code] = #pcode, Email = #mail, [Contact Number] = #ctNo
WHERE customerID = #id";
using(SqlCeConnection conDataBase = new SqlCeConnection(constring))
using(SqlCeCommand cmdDataBase = new SqlCeCommand(Query, conDataBase))
{
try
{
conDataBase.Open();
cndDataBase.Parameters.AddWithValue("#fname", this.firstTxt.Text);
cndDataBase.Parameters.AddWithValue("#sur", this.surenameTxt.Text );
cndDataBase.Parameters.AddWithValue("#addr1", this.address1Txt.Text );
cndDataBase.Parameters.AddWithValue("#addr2", this.address2Txt.Text );
cndDataBase.Parameters.AddWithValue("#county", this.countyTxt.Text );
cndDataBase.Parameters.AddWithValue("#pcode", this.postTxt.Text );
cndDataBase.Parameters.AddWithValue("#mail", this.emailTxt.Text );
cndDataBase.Parameters.AddWithValue("#ctNo", this.contactTxt.Text );
cndDataBase.Parameters.AddWithValue("#id", customerID );
int rowsUpdated = cmdDataBase.ExecuteNonQuery();
if(rowsUpdate == 0)
MessageBox.Show("No customer found to update");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
As you can see, with a parameterized query is more difficult to write a bad sql text with hidden problems and the quoting job is passed to the database code that knows better how to format the parameter values.
The only problem that you need to solve is how to retrieve the value for the customerID or some other value that you could use in the WHERE clause to uniquely identify the record of your customer
In this point you call the UpdateDatabase method that now required a UserID variable containing the key to identify your user on the table
private void editBTN_Click(object sender, EventArgs e)
{
bool notEditable = true;
if (editBTN.Text == "Update")
{
// Here you need to identify uniquely your modified user
// Usually when you load the data to edit you have this info extracted from your
// database table and you have saved it somewhere
// (of course the user should not edit in any way this value
int UserID = ... ???? (from an hidden textbox? from a global variable, it is up to you
UpdateDataBase( UserID );
I think your confusing the Update structure with an Insert.
For your update it looks like this:
update customersTBL set ([First_Name] = 'data', surename= '',[Address Line 1] = '',[Address Line 2] = '',County = '',[Post Code] = '' , Email = '';,[Contact Number] = '');
You need a where clause.
Update/Set does not put the changes in ()
After email you have a ';'
Well I have tried all you people suggested but the problem remain same
let me tell you in brief:
Form Name : AuzineForum.aspx
Has 1 GridView which displays all the field from the database using select * from QF
its working good , index is also working , the gridView Has Button and onClick I open new Form AuzineForumAnswer.aspx ..OK
I want to pick one record from AuzineForum.aspx and display on AuzineForumAnswer.aspx as well as it happens here in http://stackoverflow.com (we click on threads then the new page opens which has the question and answer on which we clicked previous) ...ok
so On AuzineForum.aspx's Button the code is
Button lb = (Button)sender;
GridViewRow row = (GridViewRow)lb.NamingContainer;
if (row != null)
{
int index = row.RowIndex; //gets the row index selected
Label AID1 = (Label)ForumQuesView.Rows[index].FindControl("AID1");
Label AID2 = (Label)ForumQuesView.Rows[index].FindControl("AID2");
Label AID3 = (Label)ForumQuesView.Rows[index].FindControl("AID3");
HyperLink Question = (HyperLink)ForumQuesView.Rows[index].FindControl("Question");
Label Questiontags = (Label)ForumQuesView.Rows[index].FindControl("Questiontags");
Label Askedby = (Label)ForumQuesView.Rows[index].FindControl("Askedby");
Response.Redirect(String.Format("AuzineForumAnswer.aspx?Question=" + Question.Text + "&Questiontags=" + Questiontags.Text + "&Askedby=" + Askedby.Text + "&AID1=" + AID1.Text + "&AID2=" + AID2.Text + "&AID3=" + AID3.Text, Server.UrlEncode(Question.Text), Server.UrlEncode(Questiontags.Text), Server.UrlEncode(Askedby.Text), Server.UrlEncode(AID1.Text), Server.UrlEncode(AID2.Text), Server.UrlEncode(AID3.Text)));
I had passes so many many parameter becuase of accuracy......
Now when I run it and click on the button so its open AuzineForumAnswer.AuzineForumAnswerand shows that record very well but problem occurs when the qtags field has "#" type of data like here tags( C#, GridView, etc) so, when the tags field has the data includin "#" chracter then it gives "Object refrence not set to Instance of an object " and if the qtags has normal data like ( specialcharacter gridview sql C ) then it open AuzineForumAnswer.aspx and show data without error
the code behind of AuzineForumAnswer.aspx is below
protected void GetAllData()
{
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["AuzineConnection"].ConnectionString;
using (SqlConnection sqlconn = new SqlConnection(connection))
{
using (SqlCommand sqlcomm = sqlconn.CreateCommand())
{
sqlcomm.CommandText = "Select * From QF where Question='" + Server.UrlDecode(Request.QueryString["Question"].ToString()) + "' And qtags='" + Server.UrlDecode(Request.QueryString["Questiontags"].ToString()) + "' And UserFullName='" + Server.UrlDecode(Request.QueryString["Askedby"].ToString()) + "' And AID1='" + Server.UrlDecode(Request.QueryString["AID1"].ToString()) + "' And AID2='" + Server.UrlDecode(Request.QueryString["AID2"].ToString()) + "' And AID3='" + Server.UrlDecode(Request.QueryString["AID3"].ToString()) + "'";
SqlDataAdapter sda = new SqlDataAdapter(sqlcomm);
DataTable dt = new DataTable();
sda.Fill(dt);
try
{
sqlconn.Open();
ForumQuesView.DataSource = dt;
ForumQuesView.DataBind();
ForumQuesView.AllowPaging = true;
}
catch (Exception ex)
{
Status.Text = ex.Message.ToString();
}
}
}
}
NOW I ALSO DO NOT UNDERSTAND What the problem here because only qtags and question is two field in which user allows to store data as they want, the question is text and qtags and all are the char field but problem is not in database the problem is here with the character #
Try changing your sql statement to include parameters and see if that works.
What you have now is not only difficult to maintain and causes errors but it’s prone to SQL injection attack quite easily.
sqlcomm.CommandText = "Select * From QF where Question=#Question And qtags=#Qtags And UserFullName=#UserName And AID1=#AID1 And AID2=#AID2 And AID3=#AID3";
sqlcomm.Parameters.Add(new SqlParameter("#Question", Server.UrlDecode(Request.QueryString["Question"])));
sqlcomm.Parameters.Add(new SqlParameter("#Qtags", Server.UrlDecode(Request.QueryString["Questiontags"])));
sqlcomm.Parameters.Add(new SqlParameter("#UserName", Server.UrlDecode(Request.QueryString["Askedby"])));
sqlcomm.Parameters.Add(new SqlParameter("#AID1", Server.UrlDecode(Request.QueryString["AID1"])));
sqlcomm.Parameters.Add(new SqlParameter("#AID2", Server.UrlDecode(Request.QueryString["AID2"])));
sqlcomm.Parameters.Add(new SqlParameter("#AID3", Server.UrlDecode(Request.QueryString["AID3"])))
;
As I know the query is fine even if you using # in the condition.
I doubt for a moment, then I tried this query
Select * From QF where Question='question 1'
And qtags='tag #1';
those query still run smooth and return the record.
I'm selecting about 20,000 records from the database and then I update them one by one.
I looked for this error and I saw that setting the CommandTimeout will help, but not in my case.
public void Initialize()
{
MySqlConnectionStringBuilder SQLConnect = new MySqlConnectionStringBuilder();
SQLConnect.Server = SQLServer;
SQLConnect.UserID = SQLUser;
SQLConnect.Password = SQLPassword;
SQLConnect.Database = SQLDatabase;
SQLConnect.Port = SQLPort;
SQLConnection = new MySqlConnection(SQLConnect.ToString());
}
public MySqlDataReader SQL_Query(string query)
{
MySqlCommand sql_command;
sql_command = SQLConnection.CreateCommand();
sql_command.CommandTimeout = int.MaxValue;
sql_command.CommandText = query;
MySqlDataReader query_result = sql_command.ExecuteReader();
return query_result;
}
public void SQL_NonQuery(string query)
{
MySqlCommand sql_command;
sql_command = SQLConnection.CreateCommand();
sql_command.CommandTimeout = int.MaxValue;
sql_command.CommandText = query;
sql_command.ExecuteNonQuery();
}
And here is my method which makes the select query:
public void CleanRecords()
{
SQLActions.Initialize();
SQLActions.SQL_Open();
MySqlDataReader cashData = SQLActions.SQL_Query("SELECT `cash`.`id`, SUM(`cash`.`income_money`) AS `income_money`, `cash_data`.`total` FROM `cash_data` JOIN `cash` ON `cash`.`cash_data_id` = `cash_data`.`id` WHERE `user`='0' AND `cash_data`.`paymentterm_id`='0' OR `cash_data`.`paymentterm_id`='1' GROUP BY `cash_data_id`");
while(cashData.Read()){
if(cashData["income_money"].ToString() == cashData["total"].ToString()){
UpdateRecords(cashData["id"].ToString());
}
}
SQLActions.SQL_Close();
}
And here is the method which makes the update:
public void UpdateRecords(string rowID)
{
SQLActions.Initialize();
SQLActions.SQL_Open();
SQLActions.SQL_NonQuery("UPDATE `cash_data` SET `end_date`='" + GetMeDate() + "', `user`='1' WHERE `id`='" + rowID + "'");
SQLActions.SQL_Close();
}
Changing the database structure is not an option for me.
I thought that setting the timeout to the maxvalue of int will solve my problem, but is looks like this wont work in my case.
Any ideas? :)
EDIT:
The error which I get is "Fatal error encoutered during data read".
UPDATE:
public void CleanRecords()
{
StringBuilder dataForUpdate = new StringBuilder();
string delimiter = "";
SQLActions.Initialize();
SQLActions.SQL_Open();
MySqlDataReader cashData = SQLActions.SQL_Query("SELECT `cash`.`id`, SUM(`cash`.`income_money`) AS `income_money`, `cash_data`.`total` FROM `cash_data` JOIN `cash` ON `cash`.`cash_data_id` = `cash_data`.`id` WHERE `user`='0' AND `cash_data`.`paymentterm_id`='0' OR `cash_data`.`paymentterm_id`='1' GROUP BY `cash_data_id`");
while (cashData.Read())
{
if (cashData["income_money"].ToString() == cashData["total"].ToString())
{
dataForUpdate.Append(delimiter);
dataForUpdate.Append("'" + cashData["id"].ToString() + "'");
delimiter = ",";
}
}
SQLActions.SQL_Close();
UpdateRecords(dataForUpdate.ToString());
}
public void UpdateRecords(string rowID)
{
SQLActions.Initialize();
SQLActions.SQL_Open();
SQLActions.SQL_NonQuery("UPDATE `cash_data` SET `end_date`='" + GetMeDate() + "', `user`='1' WHERE `id` IN (" + rowID + ")");
SQLActions.SQL_Close();
}
You may be able to use
UPDATE cash_data .... WHERE id IN (SELECT ....)
and do everything in one go. Otherwise, you could do it in two steps: first the select collects all the ids, close the connection and then do the update in obne go with all the ids.
The code for the second option might look something like this:
public void CleanRecords()
{
StringBuilder builder = new StringBuilder();
string delimiter = "";
SQLActions.Initialize();
SQLActions.SQL_Open();
MySqlDataReader cashData = SQLActions.SQL_Query("SELECT `cash`.`id`, SUM(`cash`.`income_money`) AS `income_money`, `cash_data`.`total` FROM `cash_data` JOIN `cash` ON `cash`.`cash_data_id` = `cash_data`.`id` WHERE `user`='0' AND `cash_data`.`paymentterm_id`='0' OR `cash_data`.`paymentterm_id`='1' GROUP BY `cash_data_id`");
while(cashData.Read()){
if(cashData["income_money"].ToString() == cashData["total"].ToString()){
builder.Append(delimiter);
builder.Append("'" + cashData["id"].ToString() + "'");
delimiter = ",";
}
}
SQLActions.SQL_Close();
UpdateRecords(builder.ToString());
}
public void UpdateRecords(string rowIDs)
{
SQLActions.Initialize();
SQLActions.SQL_Open();
SQLActions.SQL_NonQuery("UPDATE `cash_data` SET `end_date`='" + GetMeDate() + "', `user`='1' WHERE `id` IN (" + rowIDs + ")";
SQLActions.SQL_Close();
}
There are multiple problem:
First: You have reading information around 20K using data reader and then doing update one by one in reader itself. Reader holds the connection open until you are finished. So this is not the good way to do it. Solution: We can read the information using Data Adapter.
Second: Rather than doing one by one update, we can update in bulk in one go. There are multiple option for bulk operation. In SQL u can do either by sending information in XML format or u can use Table Valued Parameter (TVP) (http://www.codeproject.com/Articles/22205/ADO-NET-and-OPENXML-to-Perform-Bulk-Database-Opera) OR (http://dev.mysql.com/doc/refman/5.5/en/load-xml.html)