UPDATE statement is not updating results in SQL Server - c#

I am trying to update result in SQL server with below query but its not updating. If i write (update lunTime set lunOut = '2014-12-08 23:23:23.120' where empName='Mike' and
date='2014-12-08') it is updating it.
protected void btnLunOut_Click(object sender, EventArgs e)
{
SqlConnection conn1 = new SqlConnection(
"Data Source=myServer;Initial Catalog=MY_Srv;Integrated Security=True");
conn1.Open();
SqlCommand cmd = new SqlCommand(
"Update [lunTime] SET lunOut = #LunOUT where (empName=#EmpName and date=#Date)",
conn1);
cmd.Parameters.AddWithValue("#EmpName", drpDwnEmp.Text);
cmd.Parameters.AddWithValue("#LunOUT", DateTime.Now);
cmd.Parameters.AddWithValue("#Date", DateTime.Now);
cmd.ExecuteNonQuery();
conn1.Close();
drpDwnEmp.Text = string.Empty;
}

Most likely it simple does not find the record for data == DateTime.Now case.
It is unlclear what you want to achieve, but maybe some range conditions on date variable or Now.Date is the solution (assuming date is actually date only, no time portion):
cmd.Parameters.AddWithValue("#Date", DateTime.Now.Date);

Related

Second query failed to update because first query still in insert progress

private void btnSave_Click(object sender, EventArgs e)
{
using (OleDbConnection con = new OleDbConnection(cs))
{
con.Open();
cmd = new OleDbCommand(“INSERT INTO table1 ([name], [gender], [age]) VALUES ('Jeff', 'Male', 51), con);
cmd.ExecuteNonQuery();
//System.Threading.Thread.Sleep(1000); // it's working if i add a delay here
//int success = cmd.ExecuteNonQuery(); // also working if check number of query affected
//if (success > 0)
//{
// updateLastModified();
//}
updateLastModified();
}
}
public void updateLastModified()
{
using (OleDbConnection con = new OleDbConnection(cs))
{
con.Open();
cmd = new OleDbCommand("UPDATE TABLE1 SET LastModifiedTime='" + DateTime.Now.ToString() + "' WHERE name='Jeff'", con);
cmd.ExecuteNonQuery();
// this was not updated because "Jeff" cannot be found in table1 (first insert query still running)
}
}
My problem was second query not updated because first query still running.
Any better solution other than "adding a delay" or "check first query was successful" before perform second query?
This is just an example scenario, I'm not going to do in one query.
Update:
Suggestion from #a.rlx was using OleDbTransaction.Commit method. Can i do by this way without using try catch?
using (OleDbConnection con = new OleDbConnection(cs))
{
OleDbTransaction transaction = null;
con.Open();
transaction = con.BeginTransaction();
cmd = new OleDbCommand(“INSERT INTO table1 ([name], [gender], [age]) VALUES ('Jeff', 'Male', 51), con, transaction);
cmd.ExecuteNonQuery();
transaction.Commit();
updateLastModified();
}
Have you tried to start a transaction, run both SQL statements, and then commit the transaction?
https://dev.mysql.com/doc/dev/connector-net/6.10/html/M_MySql_Data_MySqlClient_MySqlConnection_BeginTransaction.htm

Asp.net Datagrid : delete one line at a time even if the same info is in the next line c#

I am trying to create a webpage that allow users to unsubscribe from receiving the report.
So far I have created the page. users are able to see all the reports that they are receiving
I have also written an "update replace" statement that, unfortunately this updates everything.
My question is how do I modify my code to only delete one line at a time even if the same info is in the next line
Please see my code below
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
System.Web.UI.WebControls.Label rollno = GridView1.Rows[e.RowIndex].FindControl("Label1") as System.Web.UI.WebControls.Label;
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UPDATE Subscriptions SET Subscriptions.ExtensionSettings = REPLACE('Subscriptions.ExtensionSettings', #ReportSearch, '') WHERE Subscriptions.ExtensionSettings like '#ReportSearch'" ;
cmd.Parameters.AddWithValue("ReportSearch", TxtSearch.Text);
cmd.Connection = con;
cmd.ExecuteNonQuery();
GridView1.EditIndex = -1;
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}

C# and Access database doesn't insert/save my data

I wrote an application with C# and MS Access. I have my form login which it works. OK. And I have an insert statement which does not throw any error, but everything I enter into my textbox doesn't get inserted into my database, and when I want to make an update, it returns the same as insert statement, I mean no error, but the row is not inserted or updated.
string stringcon = System.Configuration.ConfigurationManager.ConnectionStrings["rent"].ConnectionString;
private void validateaddmember_button_Click(object sender, EventArgs e)
{
addmember.Visible = false;
MemoryStream ms = new MemoryStream();
pictureBox4.Image.Save(ms, pictureBox4.Image.RawFormat);
byte[] a = ms.GetBuffer();
ms.Close();
OleDbConnection con = new OleDbConnection(stringcon);
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
con.Open();
cmd.CommandText = "INSERT INTO [team]([Firstname],[Lastname],[Email],[Password],[Function],[Role],[Registerdata],[Personaldescription],[Phonenumber],[Picture]) VALUES(#f,#l,#e,#p,#fu,#r,#reg,#per,#ph,#pic) ";
cmd.Parameters.AddWithValue("#f", firstname_textbox.Text);
cmd.Parameters.AddWithValue("#l", lastname_textbox.Text);
cmd.Parameters.AddWithValue("#e", email_textbox.Text);
cmd.Parameters.AddWithValue("#ph", phone_textbox.Text);
cmd.Parameters.AddWithValue("#fu", function_textbox.Text);
cmd.Parameters.AddWithValue("#r", role_dropbox.selectedValue);
cmd.Parameters.AddWithValue("#reg", DateTime.Now.ToString("dd-MM-yyyy HH: mm:ss"));
cmd.Parameters.AddWithValue("#per", richTextBox1.Text);
cmd.Parameters.AddWithValue("#p", repeatpassword_textbox.Text);
cmd.Parameters.AddWithValue("#pic", a);
cmd.ExecuteNonQuery();
con.Close();
}
And here I have in other form my update.
string stringcon = System.Configuration.ConfigurationManager.ConnectionStrings["rent"].ConnectionString;
private void bunifuFlatButton1_Click(object sender, EventArgs e)//login method
{
OleDbConnection con = new OleDbConnection(stringcon);
OleDbCommand cmd2 = new OleDbCommand();
cmd2.Parameters.Clear();
cmd2.Connection = con;
cmd2.CommandText ="update [team] set [Numberoflogin] = [Numberoflogin] + 1 where [Email]=#LEMAIL";
cmd2.Parameters.AddWithValue("#LEMAIL", materialSingleLineTextField1.Text);
con.Open();
cmd2.ExecuteNonQuery();
con.Close();
}
Along with marc_s's important note -- you switched phone and password, make sure you fix that -- you only need # in the sql string. So not
cmd.Parameters.AddWithValue("#f", firstname_textbox.Text);
but
cmd.Parameters.AddWithValue("Firstname", firstname_textbox.Text);
Use the field name (Firstname). #f is just a marker. With Access, you could write the sql string like so:
cmd.CommandText = "INSERT INTO [team]([Firstname],[Lastname],[Email],
[Password],[Function],[Role],[Registerdata],[Personaldescription],
[Phonenumber],[Picture]) VALUES(?,?,?,?,?,?,?,?,?,?)";
so when you add the parameter value, use the field name.
You could also open the connection right before cmd.ExecuteNonQuery();, like your update form.

Print My Search Results From SQL Server on label

I'm just trying to print the sum of my search on a label in form.
Story is I have 2 textboxes that will give me 2 date and searching in my database, and printing the answer of sum cost between that 2 date.
My code is :
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=localhost;Initial Catalog=SuperCalc;Integrated Security=True");
SqlCommand com = new SqlCommand();
if (con.State == ConnectionState.Closed)
{
con.Open();
com = new SqlCommand("select sum (Cost) as JameKol From TBL_Cost Where CostDate between '" + textBox1.Text + "' and '" + textBox2.Text + "' ", con);
label5.Text = com();
con.Close();
MessageBox.Show("Search is done", "Done");
}
}
com can't use as a method, so, how can I do this?
Just use ExecuteScalar which is exactly what this for. It gets first column of the first row which fits SUM function.
label5.Text = com.ExecuteScalar().ToString();
But more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
And use using statement to dispose your connection and command automatically instead of calling Close method manually.
By the way, looks like your CostDate column is character typed. Don't do it. This is a bad habit to kick. You should never keep your DateTime values as a character. Change it to datetime or better datetime2 type and pass your DateTime values directly to your parameterized query. That's why I used DateTime.Parse to parse your Text values. If it can't parse them, you can use ParseExact as well.
string conString = "Data Source=localhost;Initial Catalog=SuperCalc;Integrated Security=True";
using(var con = new SqlConnection(conString))
using(var com = con.CreateCommand())
{
com.CommandText = #"select sum (Cost) as JameKol From TBL_Cost
Where CostDate between #date1 and #date2";
com.Parameters.Add("#date1", SqlDbType.DateTime2).Value = DateTime.Parse(textBox1.Text);
com.Parameters.Add("#date2", SqlDbType.DateTime2).Value = DateTime.Parse(textBox2.Text);
con.Open();
label5.Text = com.ExecuteScalar().ToString();
}

C# Windows Form App With Ms Access Failed to Insert Data

i know this topic is already discuss many time, but i still dont get my problem solved..
ok, i have a form to insert registration data into MS Access Database (2007), but my code doesnt insert data into database, and there are no errors,
here is the code:
OleDbConnection cn = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = Data/db_klinik.mdb");
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter adapter = new OleDbDataAdapter();
private void btnSave_Click(object sender, EventArgs e)
{
string idCard = this.txtID.Text;
string name = this.txtName.Text;
DateTime dateBirth = this.dateEdit1.DateTime;
cn.Open();
cmd.CommandText = "Insert into tb_reg (id, name, dateBirth, blood_type) Values(#id,#name,#dateBirth)";
cmd.Parameters.AddWithValue("#id", idCard);
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#dateBirth", dateBirth.ToString());
adapter.InsertCommand = cmd;
int result = cmd.ExecuteNonQuery();
if (result > 0)
MessageBox.Show("Succesfully added");
else
MessageBox.Show("try again");
cn.Close();
}
the message box always show "successfully added".
I had something like this in a project of mine. Maybe it works for you:
string insertString = string.Format(CultureInfo.InvariantCulture, "INSERT INTO tb_reg VALUES ('{0}', '{1}', '{2}', {3})", idCard, name, dateBirth, blood_type);
OleDbCommand cmd = new OleDbCommand(insertString, new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = Data/db_klinik.mdb"));
cmd.Connection.Open();
int numberAdded = cmd.ExecuteNonQuery();
if (numberAdded < 1)
{
//do something, the data was not added
}
else
{
//be happy :)
}
cmd.Connection.Close();
As I said, that worked for me.
The OleDB provider does not support named parameters. Change your SQL to
cmd.CommandText = #"Insert into tb_reg (id, name, dateBirth, blood_type)
Values(?,?,?,?)";
You can name the parameters when you create them, but it will assign them to the ? placeholders in the order that they are added to the command.
Also note that you're missing a parameter for blood_type.
Whatever you do, DON'T change to use string concatenation. It open the door for SQL Injection attacks.

Categories

Resources