C# SqlCommand query with update - c#

I tried to find it. But I can't found exactly my answer. So I decide to ask this questions. I need your help.
I want add value into table value without overwriting Debit, Score column. It will add current value.
cmd = new SqlCommand("UPDATE Users SET Debit=#debit,
Score=#score
WHERE Phone=#phone", con);
con.Open();
cmd.Parameters.AddWithValue("#phone", textBox1.Text);
cmd.Parameters.AddWithValue("#debit", textBox2.Text);
cmd.Parameters.AddWithValue("#score", textBox3.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Амжилттай");
con.Close();
For example:
Table, Phone: 999 | Debit: 1500 | Score: 100 //current <br>
When I add value from textBox1 = 999, textBox2 = 500, textBox3 = 50
Table, Phone: 999, Debit: 2000, Score: 150 //updating like that
I know SQL query like that. But I don't know how to write code in SqlCommand
UPDATE Users
SET Debit = Debit + [user input], Score = Score + [user input]
WHERE = Phone
Any suggestions?
(Sorry for my horrible English I hope you guys understand What I'm trying to ask)
Thanks

If you want to add, just add:
cmd = new SqlCommand(#"UPDATE Users
SET Debit = Debit + #debit,
Score = Score + #score
WHERE Phone = #phone", con);
Please, notice verbatim string #"..." syntax. Please, do not forget about disposing (explicit Close is an antipattern):
string sql =
#"UPDATE Users
SET Debit = Debit + #debit,
Score = Score + #score
WHERE Phone = #phone";
//TODO: put the right connection string instead of "MyConnectionStringHere"
//DONE: IDisposable (SqlConnection) should be wrapped into using
using (var con = new SqlConnection("MyConnectionStringHere")) {
con.Open();
//DONE: IDisposable (SqlCommand) should be wrapped into using
using (var cmd = new SqlCommand(sql, con)) {
//TODO: AddWithValue is often a bad choice; change to Add
cmd.Parameters.AddWithValue("#phone", textBox1.Text);
cmd.Parameters.AddWithValue("#debit", textBox2.Text);
cmd.Parameters.AddWithValue("#score", textBox3.Text);
cmd.ExecuteNonQuery();
//TODO: a better policy is to read localized strings from resources
MessageBox.Show("Амжилттай");
}
}

This will help you....just try in this way..
SqlCommand cmd = new SqlCommand("UPDATE Users SET Debit = Debit + " + textBox2.Text + ", Score = Score + " + textBox3.Text + " WHERE Phone = " + textBox1.Text + "", con);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Амжилттай");
con.Close();
OR
SqlCommand cmd = new SqlCommand("UPDATE Users SET Debit = Debit + #debit, Score = Score + #score WHERE Phone = #phone", con);
con.Open();
cmd.Parameters.AddWithValue("#phone", textBox1.Text);
cmd.Parameters.AddWithValue("#debit", textBox2.Text);
cmd.Parameters.AddWithValue("#score", textBox3.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Амжилттай");
con.Close();

You can use += operator for update. Change your sql command like this;
UPDATE Users SET Debit+=#debit,
Score+=#score
WHERE Phone=#phone

Related

Check SQL for Book_Availability before issuing one (BookAvailability-1)

If I put "if, foreach, and else statement under comment //", the program works and Reduces book count by 1 from SQL database. But I want to check IF there is at least 1 available book to give. This code keeps showing me the message in "else" statement if I leave it like this. Help is needed fast, it's my final project, that is needed to be done before 23.07. :(
int book_qty = 0;
SqlCommand cmd2 = connection.CreateCommand();
cmd2.CommandType = CommandType.Text;
cmd2.CommandText = "SELECT * FROM Book_list WHERE BookName = '" + TextBoxBookName + "'";
cmd2.ExecuteNonQuery();
DataTable dt2 = new DataTable();
SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
da2.Fill(dt2);
foreach (DataRow dr2 in dt2.Rows)
{
book_qty = Convert.ToInt32(dr2["book_qty"].ToString());
}
if (book_qty > 0)
{
SqlCommand cmd = connection.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Issue_book VALUES(" + TextBoxSearchMembers.Text + ",'" + TextBoxMemberName.Text + "','" + TextBoxMemberContact.Text + "','" + TextBoxMemberEmail.Text + "','" + TextBoxBookName.Text + "', '" + DateTimePicker1.Text + "')";
cmd.ExecuteNonQuery();
SqlCommand cmd1 = connection.CreateCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "UPDATE Book_list SET BookAvailability = BookAvailability-1 WHERE BookName ='" + TextBoxBookName.Text + "'";
cmd1.ExecuteNonQuery();
MessageBox.Show("successful issue");
this.Close();
else
{
MessageBox.Show("Book not available");
}
You are only checking book_qty from the last row in your result set instead of BookAvailability for all rows. You probably want to do something like:
SqlCommand cmd2 = connection.CreateCommand();
cmd2.CommandType = CommandType.Text;
cmd2.CommandText = "SELECT BookAvailability FROM Book_list WHERE BookName = '" + TextBoxBookName + "'";
var result = cmd2.ExecuteScalar();
book_qty = Convert.ToInt32(result);
You need to make sure that there is only one book with the given bookname available.
In that case just correcting this one line in your code would help as well:
book_qty = Convert.ToInt32(dr2["book_qty"].ToString());
to
book_qty = Convert.ToInt32(dr2["BookAvailability"].ToString());
Otherwise you'd need to query SUM(BookAvailability), but the following code would decrease the amount of books for multiple books at once, that wouldn't be good.
Untested code. I don't have your database. Comments and explanation in line.
private void OPCode()
{
try
{
//keep your connections close to the vest (local)
using (SqlConnection connection = new SqlConnection())
//a using block ensures that your objects are closed and disposed
//even if there is an error
{
using (SqlCommand cmd2 = new SqlCommand("SELECT BookAvailability FROM Book_list WHERE BookName = #BookName", connection))
{
//Always use parameters to protect from sql injection
//Also it is easier than fooling with the single quotes etc.
//If you are referring to a TextBox you need to provide what property is
//being accessed. I am not in a WPF right now and not sure if .Text
//is correct; may be .Content
//You need to check your database for correct data type and field size
cmd2.Parameters.Add("#BookName", SqlDbType.VarChar, 100).Value = TextBoxBookName.Text;
//A select statement is not a non-query
//You don't appear to be using the data table or data adapter
//so dump them extra objects just slow things dowm
connection.Open();
//Comment out the next 2 lines and replaced with
//Edit Update
//var returnVal = cmd2.ExecuteScalar() ?? 0;
//if ((int)returnVal > 0)
//*************************************************************
//Edit Update
//*************************************************************
//in case the query returns a null, normally an integer cannot
//hold the value of null so we use nullable types
// the (int?) casts the result of the query to Nullable of int
Nullable<int> returnVal = (int?)cmd2.ExecuteScalar();
//now we can use the .GetValueOrDefault to return the value
//if it is not null of the default value of the int (Which is 0)
int bookCount = returnVal.GetValueOrDefault();
//at this point bookCount should be a real int - no cast necessary
if (bookCount > 0)
//**************************************************************
//End Edit Update
//**************************************************************
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO issue_book VALUES(#SearchMembers etc", connection))
{
//set up the parameters for this command just like the sample above
cmd.Parameters.Add("#SearchMembers", SqlDbType.VarChar, 100).Value = TextBoxSearchMembers.Text;
cmd.ExecuteNonQuery();
}
using (SqlCommand cmd1 = new SqlCommand("UPDATE Book_list SET BookAvailability = BookAvailability-1 WHERE BookName = #BoxBookName;", connection))
{
cmd1.Parameters.Add("#BoxBookName", SqlDbType.VarChar, 100);
cmd1.ExecuteNonQuery();
}
MessageBox.Show("success");
this.Close();
}
else
{
MessageBox.Show("Book not available");
}
}
}
}
catch (Exception exc)
{
MessageBox.Show(exc.ToString());
}
}

eliminating duplicate records insertion into database

The below is my code to insert gridview data into a database. However, using this I want to check and restrict insertion into the database where records have the same name, location, education and salary. If all of these are the same and those already present in database they should not get inserted. If any one column is different then they should get inserted.
protected void btn_insert_Click(object sender, EventArgs e)
{
foreach (GridViewRow g1 in GridView1.Rows)
{
SqlConnection con = new SqlConnection(connStr);
cmd = new SqlCommand("insert command", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
UploadStatusLabel.Text = "Records Inserted Successfully";
}
I think hitting the database inside a for loop is a very bad idea when you have other options. I'm not tackling this issue in the below sample.
Your code may be subject to SQL Injection, you need to use parameters to pass your values. If someone filled the input with ";DROP TABLE OpenOfficetext;" and they have DROP permissions, it will be a problem if you're just concatenating strings.
To avoid duplicates, you can check first if a similar record exists.
foreach (GridViewRow g1 in GridView1.Rows)
{
string insertCommand = "insert into OpenOfficetext(Name, Location, Education, Salary) values(#p1, #p2, #p3, #p4)";
string selectCommand = "SELECT COUNT(*) FROM OpenOfficetext WHERE Name = #p1 AND Location = #p2 AND Education = #p3 AND Salary = #p4";
SqlConnection con = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand(selectCommand, con);
con.Open();
cmd.Parameters.AddWithValue("#p1", g1.Cells[0].Text);
cmd.Parameters.AddWithValue("#p2", g1.Cells[1].Text);
cmd.Parameters.AddWithValue("#p3", g1.Cells[2].Text);
cmd.Parameters.AddWithValue("#p4", g1.Cells[3].Text);
if (Convert.ToInt32(cmd.ExecuteScalar()) == 0)
{
cmd.CommandText = insertCommand;
cmd.ExecuteNonQuery();
}
con.Close();
}
please use the below code
if not exist (select * from OpenOfficetext where Name='" + g1.Cells[0].Text + "' and Location='" + g1.Cells[1].Text + "' and Education = '" + g1.Cells[2].Text + "' and Salary = '" + g1.Cells[3].Text + "' )
Begin
SqlConnection con = new SqlConnection(connStr);
cmd = new SqlCommand("insert into OpenOfficetext(Name,Location,Education,Salary) values ('" + g1.Cells[0].Text + "','" + g1.Cells[1].Text + "','" + g1.Cells[2].Text + "','" + g1.Cells[3].Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
End

store datetimepicker value of c# into mysql database

Hello I want to store datetimepicker value into mysql database my code is given below
dtpDate = datetimepicker1.value.date;
dtpTime = datetimepicker2.value.Timeofday;
MySqlCommand cmd = new MySqlCommand("INSERT INTO schedule_days(schedule_name,start_time,status,days,start_date,connector_id) VALUES ('" + name + "','" + dtpTime + "','" + s + "','" + day + "','"+dtpDate+"','" + chkArray[i].Tag + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
but no value is being stored at database
and at that place there is unable to read data comes.
what may be the problem?
The Value is not being entered at MySQL database because there is mistake in your query at dtpTime and dtpDate fields.
you shout replace it whith dtpTime.Value.TimeofDay and dtpDate.Value.Date ane new query will be like this
dtpDate = datetimepicker1.value.date;
dtpTime = datetimepicker2.value.Timeofday;
MySqlCommand cmd = new MySqlCommand("INSERT INTO schedule_days(schedule_name,start_time,status,days,start_date,connector_id) VALUES ('" + name + "','" + dtpTime.Value.TimeofDay + "','" + s + "','" + day + "','"+dtpDate.Value.Date.ToString("yyyy-MM-dd HH:mm")+"','" + chkArray[i].Tag + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Well, it may not be the cause of the problem (are there any exceptions? What does ExecuteNonQuery return?) but you should definitely not be building up your SQL like this. It leads to SQL injection attacks, as well as data conversion problems.
Instead, you should use parameterized SQL:
using (MySqlConnection conn = new MySqlConnection(...))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand(
"INSERT INTO schedule_days(schedule_name,start_time,status,days,start_date,connector_id) " +
"VALUES (#name, #time, #status, #days, #date, #connector)", conn))
{
cmd.Parameters.Add("#name", MySqlDbType.VarChar).Value = name;
cmd.Parameters.Add("#time", MySqlDbType.Time).Value = dtpTime;
cmd.Parameters.Add("#status", MySqlDbType.VarChar).Value = s;
cmd.Parameters.Add("#days", MySqlDbType.Int32).Value = day;
cmd.Parameters.Add("#date", MySqlDbType.Date).Value = dtpDate;
cmd.Parameters.Add("#connector", MySqlDbType.VarChar).Value = chkArray[i].Tag;
int insertedRows = cmd.ExecuteNonQuery();
// TODO: Validate that insertedRows is 1?
}
}
I've guessed at the data types - please check them against your actual database.
Using NuGet Package MySql.Data 6.6.4.
Currently MySqlParameter does not support unnamed parameters. Parameters must begin with with a ?.
Example:
command.Parameters.AddWithValue("?Parameter", value);
Something like this should work. Avoid string concatenation with Sql because that can lead to security risks.
dtpDate = datetimepicker1.value.date.ToString("yyyy-MM-dd HH:mm"); //Formatted Date for MySql
dtpTime = datetimepicker2.value.Timeofday;
using(var connection = new MySqlConnection(connectionString))
{
using(var command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO schedule_days(schedule_name,start_time,status,days,start_date,connector_id) VALUES ( ?ScheduleName, ?StartTime, ?Status, ?Days, ?StartDate, ?ConnectorId )";
command.Parameters.AddWithValue("?ScheduleName", name);
command.Parameters.AddWithValue("?StartTime", dtpTime);
command.Parameters.AddWithValue("?Status", s);
command.Parameters.AddWithValue("?Days", day);
command.Parameters.AddWithValue("?StartDate", dtpDate);
command.Parameters.AddWithValue("?ConnectorId", chkArray[i].Tag);
connection.Open();
command.ExecuteNonQuery();
}
}

inserting multiple values from C# into one row in a SQL table

I have a table which i want to store all the outputs into one row seperated by a space(eg "textbox1 textbox2 textbox3". How would i do this? At the moment its trying to put them into different columns. Giving me an error stating im using fewer columns.
}
using (SqlCommand cmd = new SqlCommand("INSERT INTO [user] (solution) VALUES (#textbox1, #textbox2, #textbox3)", cn))
{
cmd.Parameters.AddWithValue("#textbox1", textBox1.Text);
cmd.Parameters.AddWithValue("#textbox2", textBox2.Text);
cmd.Parameters.AddWithValue("#textbox3", textBox3.Text);
cmd.ExecuteNonQuery(); // or int affected = cmd.ExecuteNonQuery()
MessageBox.Show("Success!");
}
}
Try this:
using (SqlCommand cmd = new SqlCommand("INSERT INTO [user] (solution) VALUES (#text)", cn))
{
cmd.Parameters.AddWithValue("#text", textBox1.Text + " " + textBox2.Text + " " + textBox3.Text);
cmd.ExecuteNonQuery(); // or int affected = cmd.ExecuteNonQuery()
MessageBox.Show("Success!");
}
You are inserting data in more column than you have specified so I think you have got the error in that part. So, make some modification in code to remove the error:
}
using (SqlCommand cmd = new SqlCommand("INSERT INTO [user] (solution) VALUES (#textbox1+' '+ #textbox2+' '+ #textbox3)", cn))
{
cmd.Parameters.AddWithValue("#textbox1", textBox1.Text);
cmd.Parameters.AddWithValue("#textbox2", textBox2.Text);
cmd.Parameters.AddWithValue("#textbox3", textBox3.Text);
cmd.ExecuteNonQuery(); // or int affected = cmd.ExecuteNonQuery()
MessageBox.Show("Success!");
}
}

Check for value in Mysql if else update value

I have a database with some columns named UPC title Description and Quantity. i am trying to do a check to see if a UPC number already exists in the column and IF IT DOES then update the quantity of that entry by 1 here is what i have so far:
MySqlConnection connection = new MySqlConnection(MyConString);
connection.Open();
MySqlCommand command = connection.CreateCommand();
command.CommandText = "INSERT INTO tableName " +
"(upc, title, description, quantity) " +
"VALUES " +
"(#upc, #title, #description, #quantity)";
MySqlCommand upcCheck = connection.CreateCommand();
upcCheck.CommandText = "Select COUNT (*) FROM tableName WHERE " +
"(upc=#upc) LIMIT 1";
upcCheck.Parameters.AddWithValue("#upc", upc.Text); //Checks for duplicate UPCs
MySqlDataReader check = upcCheck.ExecuteReader();
if( check.Read() != false)
{
command.Parameters.AddWithValue("#quantity",++); //not sure how to word it right
}
command.Parameters.AddWithValue("#upc", upc.Text); //adding parameters SAFELY to the statement
command.Parameters.AddWithValue("#title", titlename);
command.Parameters.AddWithValue("#description", descname);
command.Parameters.AddWithValue("#quantity", "1");
MySqlDataReader result = command.ExecuteReader();
I'm just not sure how to word it to do the check.
UPDATE! Here is the working code.
MySqlConnection connection = new MySqlConnection(MyConString);
connection.Open();
MySqlCommand updatecommand = connection.CreateCommand();
updatecommand.CommandText = "UPDATE tableName Set quantity = quantity +1 " +
"WHERE upc = #upc";
updatecommand.Parameters.AddWithValue("#upc", upc.Text);
using (MySqlDataReader updateResult = updatecommand.ExecuteReader())
{
if (updateResult.RecordsAffected == 0)
{
affected = true;
}
else
{
affected = false;
}
}
if(affected == true)
{
MySqlCommand command = connection.CreateCommand();
command.CommandText = "INSERT INTO tableName " +
"(upc, title, description, quantity) " +
"VALUES " +
"(#upc, #title, #description, #quantity)";
command.Parameters.AddWithValue("#upc", upc.Text);
command.Parameters.AddWithValue("#title", titlename);//adding parameters SAFELY to the statement
command.Parameters.AddWithValue("#description", descname);
command.Parameters.AddWithValue("#quantity", "1");
MySqlDataReader result = command.ExecuteReader();
}
Although I've not worked specifically with MySqlDataReader, I would slightly change the queries around... the otherwise format (parameterization) you have for the insert is completely fine.
Although the ON DUPLICATE KEY UPDATE provided by Hristo is cool, you would be missing the other column elements for your record. I would change to..
MySqlCommand command = connection.CreateCommand();
command.CommandText = "UPDATE tableName Set Quantity = Quantity +1 " +
"WHERE upc = #upc"
command.Parameters.AddWithValue("#upc", upc.Text);
** Dont know how the value / status will be returned from the MySqlDataReader, but
result = command.ExecuteReader();
if( the status indicates it actually succeeded in an update,
or how many records were updated > 0 )
return; // you've just increased the counter...
OTHERWISE, it was not on file.. continue with the rest of your SQL-insert command, we can overwrite the last command instance...
command = connection.CreateCommand();
command.CommandText = "INSERT INTO tableName " +
"(upc, title, description, quantity) " +
"VALUES " +
"(#upc, #title, #description, #quantity)";
command.Parameters.AddWithValue("#upc", upc.Text);
command.Parameters.AddWithValue("#title", titlename);
command.Parameters.AddWithValue("#description", descname);
command.Parameters.AddWithValue("#quantity", "1");
result = command.ExecuteReader();
If UPC is you primary key you can use INSERT ON DUPLICATE KEY UPDATE functionality of MySQL database. If you dont want to INSERT the new UPC just run an UPDATE query if there is no such row if wont affect the data in the table.
UPDATE <tablename> SET quantity=quantity+1 WHERE UPC='<upc>'

Categories