SQL code for delete Row? - c#

please anyone to explain me what is the problem with following code why didn't delete Table Row.
con.Open();
SqlCommand cmd = new SqlCommand("delete from RentTable where CID = '" + ID + "' and MID = '" + MID + "' )", con);
int result = cmd.ExecuteNonQuery();
if (result == 1)
{
Message = "succsess";
}
else
{
Message = "!";
}
con.Close();

75% of all these types of problems would be fixed if people loaded their queries into a string variable first then printed them out for debugging purposes :-)
You have a closing parenthesis ) at the end of your query which shouldn't be there.

your sql appears to have a closing brace in it without having an opening brace.
change it to
SqlCommand cmd = new SqlCommand(
"delete from RentTable where CID = '" + ID + "' and MID = '" + MID + "'"
, con);

your command is:
SqlCommand cmd = new SqlCommand(
"delete from RentTable where CID = '" + ID + "' and MID = '" + MID + "' )",
con
);
while it should be:
SqlCommand cmd = new SqlCommand(
"delete from RentTable where CID = '" + ID + "' and MID = '" + MID + "' ",
con
);
(you should remove the ")" from your command)

Change row with sql command creation to this:
/* look at this - no need to wrap string values with
apostrophes since you use parameters */
string query = "delete from RentTable where CID = #id and MID = #mid";
/* create command */
SqlCommand cmd = new SqlCommand(query);
/* set parameters */
cmd.Parameters.AddWithValue("#id", ID);
cmd.Parameters.AddWithValue("#mid", MID);
This's not only solve your problem. This'll help you to prevent problems like it in the future if you'll be using parameters instead concatenation.
PS. Also you have "succsess" misspelled if english word was meant ;)

Related

Query doesn't store my registration form data asp.net

I actually new in asp.net c# I want to know why this code below doesn't work.
All I want to do is store data form into a SQL Server database.
I have 2 tables and I want the data form entered stored in the database. Look at the select statement for retrieving the primary key to store it as a foreign key in the other table
String q = "Insert into dbo.requests(request_date,request_type,visit_date,reason,user_id,status_id)values('" + DateTime.Now.ToString() + "','" + DropDownList1.SelectedValue.ToString() + "','" + TextBox8.Text.ToString() + "','" + TextBox9.Text.ToString() + "','"+ 1+"','"+ 2+"')";
SqlCommand cmd = new SqlCommand(q, con);
cmd.ExecuteNonQuery();
con.Close();
con2.Open();
if (con2.State == System.Data.ConnectionState.Open)
{
String a = "select top 1 request_id from dbo.requests where request_date= CAST(GETDATE() AS DATE and user_id=999 order by request_id DESC ";
SqlCommand cmd2 = new SqlCommand(a, con2);
int r = cmd2.ExecuteNonQuery();
}
con2.Close();
con3.Open();
if (con3.State == System.Data.ConnectionState.Open)
{
String b = "INSERT into dbo.visitor(visitor_Fname,visitor_Mname,visitor_family_name,visitor_id,visitor_mobile,request_id,place_of_work,country_name) values ('" + TextBox1.Text.ToString() + "','" + TextBox2.Text.ToString() + "','" + TextBox3.Text.ToString() + "','" + TextBox4.Text.ToString() + "' , '" + TextBox5.Text.ToString() + "','r', '" + TextBox6.Text.ToString() + "', '" + TextBox7.Text.ToString() + "' )";
SqlCommand cmd3 = new SqlCommand(b, con3);
cmd3.ExecuteNonQuery();
}
You should change it
int r = cmd2.ExecuteNonQuery();
to
int r = (int)cmd2.ExecuteScalar();
To retrieve selecting only one field use ExecuteScalar instead of ExecuteNonQuery. ExecuteNonQuery doesn't return selecting fields.
Just store request_id in variable using data table.
Actually you are storing 'r' in table which is wrong. Try to store request_id from select statement in variable it will be work .

Insert data into table(from select) using 2 DataGridView c# windowsForm

Please help me to understand where I go wrong. ok let's go!
2 DataGridViews, in first I'm store services in second order list.
when I push button Save, this code will happen:
public void insert_sales_list()
{
conn.Open();
foreach (DataGridViewRow row in dgvService.SelectedRows)
{
SQLiteCommand cmd = new SQLiteCommand("insert into sales_list (sales_created_date, sales_created_name, emp_name, cust_phone, cust_name, planned_date, planned_time, service_name, discount, price, order_id) values (#ocd, #ocn, #emp, #c_phone, #c_name, #p_date, #p_time, #sn, #disc, #price, #o_id)", conn);
cmd.Parameters.AddWithValue("#ocd", DateTime.Now);
cmd.Parameters.AddWithValue("#ocn", lblLoginUser.Text);
cmd.Parameters.AddWithValue("#emp", dgvOrderList.CurrentRow.Cells[1].Value.ToString());
cmd.Parameters.AddWithValue("#c_phone", dgvOrderList.CurrentRow.Cells[2].Value.ToString());
cmd.Parameters.AddWithValue("#c_name", dgvOrderList.CurrentRow.Cells[3].Value.ToString());
cmd.Parameters.AddWithValue("#p_date", dgvOrderList.CurrentRow.Cells[5].Value);
cmd.Parameters.AddWithValue("#p_time", dgvOrderList.CurrentRow.Cells[6].Value.ToString());
cmd.Parameters.AddWithValue("#sn", row.Cells[0].Value.ToString());
cmd.Parameters.AddWithValue("#disc", dgvOrderList.CurrentRow.Cells[4].Value.ToString());
cmd.Parameters.AddWithValue("#price", row.Cells[1].Value.ToString());
cmd.Parameters.AddWithValue("#o_id", dgvOrderList.CurrentRow.Cells["order id"].Value);
cmd.ExecuteNonQuery();
string sql = "update order_list set status = 'Saved' where id = '" + dgvOrderList.CurrentRow.Cells["order id"].Value + "'";
cmd = new SQLiteCommand(sql, conn);
cmd.ExecuteNonQuery();
}
conn.Close();
By this code you see that I just insert data from Order List to Sales List, user choose service or services from DataGridView.Service, he can take any service from the list.
This code works very well.
Next step. I have another table where each service have own materials, for example - men's haircut have soap, shampoo and tissue paper in materials. And I need to insert these data in SalesMaterials Table. And I think code is wrong, please help me to find this error? code:
public void insert_sales_materials()
{
conn.Open();
foreach (DataGridViewRow row in dgvService.SelectedRows)
{
string Query = "insert into sales_list_materials(order_id, material_id, norma, created_name, creation_date) " +
"values( select '" + dgvOrderList.CurrentRow.Cells["order id"].Value + "', a.material_id, a.norma, '" + lblLoginUser.Text + "', '" + DateTime.Now + "' from service_materials a where a.service_id = '" + row.Cells[2].Value + "')";
SQLiteCommand cmd = new SQLiteCommand(Query, conn);
cmd.ExecuteNonQuery();
}
conn.Close();
}
Error:
Additional information: SQLite error
near "select": syntax error
Ok I got it!
when you insert data with select, please did not use word values =))
correct code for all of you:
public void insert_sales_materials()
{
conn.Open();
foreach (DataGridViewRow row in dgvService.SelectedRows)
{
string Query = "insert into sales_list_materials(order_id, material_id, norma, created_name, creation_date) " +
"select '" + dgvOrderList.CurrentRow.Cells["order id"].Value + "', a.material_id, a.norma, '" + lblLoginUser.Text + "', '" + DateTime.Now + "' from service_materials a where a.service_id = '" + row.Cells[2].Value + "'";
SQLiteCommand cmd = new SQLiteCommand(Query, conn);
cmd.ExecuteNonQuery();
}
conn.Close();
}

Making a reservation button

I'm making a class reservation website and having trouble with creating the button.
I would like to customer to insert two details session into two textboxes, session type "class" or "workshop" and date & time and they will be able to see that information from the DataGridView displayed.
Once they hit the "Reserve" button the button will run a query where it'll add the chosen session from Session table to Reservation table. However my code executes with no errors but does not update the "Reservation" table.
here's my code:
OleDbConnection myConnection = GetConnection();
OleDbCommand cmd = myConnection.CreateCommand();
string query = "select COUNT(*) from [Yoga-Session] where [session type] = '" + txt_type.Text + "' and duration = '" + txt_datetime.Text + "';";
OleDbCommand command = new OleDbCommand(query, myConnection);
myConnection.Open();
int rows1 = (Int32)command.ExecuteScalar();
if (rows1 >= 1)
{
cmd = new OleDbCommand("Select session_id from [yoga-session] where [session type] = '" + txt_type.Text + "' and duration = '" + txt_datetime.Text +"';",myConnection);
int classId = (Int32)command.ExecuteScalar();
cmd = new OleDbCommand("select client_id from client where name = '" + Session["[name]"] + "';", myConnection);
int clientID = (Int32)command.ExecuteScalar();
string query1 = "insert into reservation (session_id, client_id, client_name) values ('" + classId + "','" + clientID + "','" + Session["[name]"].ToString() + "');";
cmd = new OleDbCommand(query1, myConnection);
cmd.ExecuteNonQuery();
Response.Write("Reservation successful");
Response.Redirect("reservation.aspx");
myConnection.Close();
}
}
}
int classId = (Int32)cmd.ExecuteNonQuery();
int clientID = (Int32)cmd.ExecuteNonQuery();
You need to use cmd.ExecuteScalar() to get session_id and client_id values. ExecuteNonQuery returns you no of rows affected by the SQL query.
Also see what #Sherantha pointed out.
ExecuteNonQuery() is not for SELECT commands. To get a field value from SELECT command we need to use ExecuteScalar().
Try replacing;
int rows1 = (Int32)command.ExecuteScalar();
Just a small headsup before I compose my real answer (because I don't have rep to comment)
Firstly: Use Prepared Statements. They help immensely in reducing errors from typing SQL queries, as well as a way to prevent SQL Injection Attacks in real-world situations.
Secondly: While not really needed in most database types, it is recommended that a naming convention is strictly uniform in your code.
Well aside from that, I will get to the real answer now.
Looking at the code, I am assuming that classID and clientID are integers, but in your code, it looks like they are parsed as strings due to the ' ' characters. Do not use the characters when inserting integers.
EDIT: is [session type] meant to be [session_type]?
You should use query1 instead of query.
string query1 = "insert into reservation (session_id, client_id, client_name) values ('" + classId + "','" + clientID + "','" + Session["[name]"].ToString() + "');";
cmd = new OleDbCommand(query1, myConnection);// not query but query1
cmd.ExecuteNonQuery();
Response.Write("Reservation successful");
PS: Use sql data reader to select data.
cmd = new OleDbCommand("Select session_id from [yoga-session] where [session type] = '" + txt_type.Text + "' and duration = '" + txt_datetime.Text +"';",myConnection);
SqlDataReader rdr = cmd.ExecuteReader();
int classId = 0;
while (rdr.Read())
{
clientID = Convert.ToInt32(rdr["session_id"]);
}

C# Sql Server update with multiple where clauses and multiple id fields

I am getting Unclosed quotation mark after the character string ''. and I have tried everything any help would be greatly appreciated.
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["sipConnectionString"].ConnectionString);
protected void Button1_Click(object sender, EventArgs e)
{
conn.Open();
string query = "select dealercode, dropdate, couponno from coupon where dealercode = '" + DEALERCODETextBox.Text + "' and dropdate = '" + DROPDATETextBox.Text + "' and COUPONNO = '" + COUPONCOUNTTextBox.Text +"','";
SqlCommand cm = new SqlCommand(query, conn);
cm.Parameters.AddWithValue("#couponcount", COUPONCOUNTTextBox.Text);
cm.Parameters.AddWithValue("#totalrev", GRANDTOTALTextBox.Text);
cm.ExecuteNonQuery();
conn.Close();
In the last of your query string
and COUPONNO = '" + COUPONCOUNTTextBox.Text +"','";
replace +"','"; with "'";
Note: Your query string also lack of Parameters
You use paramters to add the values, but you don't use the parameters in the query:
string query = "select dealercode, dropdate, couponno from coupon where dealercode = #dealercode and dropdate =#dropdate and COUPONNO = #couponcount;";
SqlCommand cm = new SqlCommand(query, conn);
cm.Parameters.AddWithValue("#couponcount", COUPONCOUNTTextBox.Text);
cm.Parameters.AddWithValue("#dealercode ", DEALERCODETextBox.Text);
cm.Parameters.AddWithValue("#dropdate ", DROPDATETextBox.Text);
Replace with this line:
string query = "select dealercode, dropdate, couponno
from coupon where dealercode = '" + DEALERCODETextBox.Text + "'
and dropdate = '" + DROPDATETextBox.Text + "'
and COUPONNO = '" + COUPONCOUNTTextBox.Text +"'";
SqlCommand cm = new SqlCommand(query, conn);

Int Value in C# does not match with SQL count() value

I'm trying to pass a value from my SQL query count() to c# int Tech_Count but it's displaying different. If I only run the query count, it return 3 but in c#, it's showing -1. Here's my code.
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;Integrated Security=True; AttachDbFilename=C:\Users\anthonyhau\Documents\Lawn Mower\LawnMowerDatabase\LawnMowerDatabase\Database1.mdf");
con.Open();
SqlCommand cmd1 = new SqlCommand("update Tech set Customer_Count = (select IdAndCnt.cnt from (select Tech_Id,count (Tech_id) as cnt from Customers group by Tech_Id ) as IdAndCnt where Tech.Tech_Id = IdAndCnt.Tech_Id)", con);
SqlCommand cmd = new SqlCommand("INSERT INTO Customers (First_Name, Last_Name, Street, City, State, Zip, Phone, Date_Started) VALUES ('" + textBox1.Text + "', '" + textBox2.Text + "', '" + textBox3.Text + "', '" + textBox4.Text + "', '" + textBox5.Text + "', '" + textBox6.Text + "', '" + textBox7.Text + "', '" + dateTimePicker1.Value.ToString("MM/dd/yyyy") + "')", con);
SqlCommand techcnt = new SqlCommand("Select count(Tech_Id) From Tech", con);
cmd1.ExecuteNonQuery();
cmd.ExecuteNonQuery();
int Tech_Count = techcnt.ExecuteNonQuery();
textBox8.Text = Tech_Count.ToString();
con.Close();
I think you have to use ExecuteScalar instead of executenonquery and it will solve your problem.
int Tech_Count = (int)techcnt.ExecuteScalar();
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar(v=vs.110).aspx
That's because ExecuteNonQuery does not return the count like that for SELECT statements:
From MSDN
For UPDATE, INSERT, and DELETE statements, the return value is the
number of rows affected by the command. When a trigger exists on a
table being inserted or updated, the return value includes the number
of rows affected by both the insert or update operation and the number
of rows affected by the trigger or triggers. For all other types of
statements, the return value is -1.
Why are you using ExecuteNonQuery if you are in fact executing a query?? Objects in classes are pretty self explanatory. ExecuteNonQuery is used for update,deletes and inserts so it returns the affected rows. Try this on for size:
SqlCommand techcnt = new SqlCommand("Select #count:=count(Tech_Id) From Tech", con);
techcnt.Parameters.Add("#count", SqlDbType.Int).Direction = ParameterDirection.Output;
techcnt.CommandType = CommandType.Text;
techcnt.ExecuteScalar();
textBox8.Text = techcnt.Parameters["#count"].Value.ToString();
or something shorter like this:
SqlCommand techcnt = new SqlCommand("Select count(Tech_Id) From Tech", con);
textBox8.Text = techcnt.ExecuteScalar().ToString();

Categories