Making a reservation button - c#

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"]);
}

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 .

Using two different columns in a Where statement depending on if one is empty

I've currently got a WHERE clause in a SQL string that looks like this:
CmdTxt = CmdTxt + "Where FA.CSE_LAN = '" + UID + "' ";
It eventually culminates in a call to Oracle:
OracleCommand cmd = new OracleCommand(CmdTxt, connection);
cmd.Connection = connection;
cmd.CommandText = CmdTxt;
cmd.CommandType = CommandType.Text;
OracleDataAdapter da = new OracleDataAdapter(cmd);
da.Fill(dt);
What I now need to do is change that WHERE logic, so that it first looks at a column called FA.BUILD_CSE_LAN. If that has a value, it will use that column in the WHERE clause.
If it doesn't have a value, it will use the column FA.CSE_LAN in the WHERE clause.
How can I do this? I'm using C# code-behind in an ASP.Net environment against an Oracle 12c database, if any of that is important.
I am no expert on oracle but I would try something like this.
CmdTxt = CmdTxt + "Where FA.BUILD_CSE_LAN = #UID OR ( FA.BUILD_CSE_LAN IS NULL AND FA.CSE_LAN = #UID)";
That way it if your build field is null, no value, it checks the other one.
And declare #UID as a parameter on your command to avoid injection or special character issues.
This doc on Oracle might help: NVL or COALESCE could help here.
CmdTxt = CmdTxt + "Where NVL(FA.BUILD_CSE_LAN, FA.CSE_LAN) = '" + UID + "' ";
or
CmdTxt = CmdTxt + "Where COALESCE(FA.BUILD_CSE_LAN, FA.CSE_LAN) = '" + UID + "' ";

C# How to update bool in a database a sql query

How to update bool in a database a sql query
below is the code i have but i am unsure of how to implement the checkbox.
Thank you for any help.
i have updated the code to remove the sql injection problems.
con.Open();
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From ", comboBox1.Text), con);
cmd.CommandType = CommandType.Text;
string tableName = comboBox1.Text.ToString();
cmd.CommandText = #"UPDATE [" + tableName + "] SET"
+"People_Call_Status = #People_Call_Status,"
+"Research_Date=#Research_Date,"
+ "tblCompanies_Area_Dialling_Code = #tblCompanies_Area_Dialling_Code,"
+ "Work_Number = #Work_Number,"
+ "building_Address = #building_Address,"
+ "[Street Address] = #[Street Address],"
+ "suburb = #suburb,"
+ "city = #city,"
+ "res_Code = #res_Code,"
+ "industry_Vertical_ID = #industry_Vertical_ID,"
+ "pO_Box = #pO_Box,"
+ "post_Office = #post_Office,"
+ "postal_Code = #postal_Code,"
+ "country_ID = #country_ID,"
+ "province_ID = #province_ID," //this line
+ "prospect = #prospect"
+ "WHERE Company_ID = #Company_ID ";
cmd.Parameters.AddWithValue("#People_Call_Status", Status_textBox1.Text);
cmd.Parameters.AddWithValue("#Research_Date", Date_textBox.Text);
cmd.Parameters.AddWithValue("#Company_Name", company_NameTextBox.Text);
cmd.Parameters.AddWithValue("#tblCompanies_Area_Dialling_Code", tblCompanies_Area_Dialling_CodeTextBox.Text);
cmd.Parameters.AddWithValue("#Work_Number", work_NumberTextBox.Text);
cmd.Parameters.AddWithValue("#building_Address", building_AddressTextBox.Text);
cmd.Parameters.AddWithValue("#[Street Address]", street_AddressTextBox.Text);
cmd.Parameters.AddWithValue("#suburb", suburbTextBox.Text);
cmd.Parameters.AddWithValue("#city", cityTextBox.Text);
cmd.Parameters.AddWithValue("#res_Code", res_CodeTextBox.Text);
cmd.Parameters.AddWithValue("#industry_Vertical_ID", industry_Vertical_IDTextBox.Text);
cmd.Parameters.AddWithValue("#pO_Box", pO_BoxTextBox.Text);
cmd.Parameters.AddWithValue("#post_Office", post_OfficeTextBox.Text);
cmd.Parameters.AddWithValue("#postal_Code", postal_CodeTextBox.Text);
cmd.Parameters.AddWithValue("#country_ID", country_IDTextBox.Text);
cmd.Parameters.AddWithValue("#province_ID", province_IDTextBox.Text);
cmd.Parameters.AddWithValue("#prospect", prospectCheckBox.Checked);
cmd.Parameters.AddWithValue("#Company_ID", company_IDTextBox.Text);
cmd.ExecuteNonQuery();
{
MessageBox.Show("Update Success!");
con.Close();
}
In SQL Server, bool is mapped as a bit datatype with 0 and 1 values.
So what you need to do is:
"', prospect = '" + prospectCheckBox.Checked ? 1 : 0
Side-Note:
Don't concatenate strings to build up your query from user data input, this is vulnerable to SQL injection. Instead, use parameterized queries or stored procedures.
What DBMS platform are you using, and can you show the DDL for the table?
I can't guarantee this will work, but instead of using AddWithValue try using the Add method with explicit types declared:
cmd.Parameters.Add(new OleDbParameter("#People_Call_Status", OleDbType.VarChar));
cmd.Parameters.Add(new OleDbParameter("#Research_Date", OleDbType.VarChar));
...
cmd.Parameters.Add(new OleDbParameter("#prospect", OleDbType.Boolean));
cmd.Parameters.Add(new OleDbParameter("#Company_ID", OleDbType.VarChar));
cmd.Parameters[0].Value = Status_textBox1.Text;
cmd.Parameters[1].Value = Date_textBox.Text;
...
cmd.Parameters[16].Value = prospectCheckBox.Checked;
cmd.Parameters[17].Value = company_IDTextBox.Text;
Also, with regards to SQL Injection, you still have a theoretical vulnerability:
cmd.CommandText = #"UPDATE [" + tableName + "] SET"
+ "People_Call_Status = #People_Call_Status,"
+ "Research_Date=#Research_Date,"
...
+ "prospect = #prospect"
+ "WHERE Company_ID = #Company_ID ";
I realize it's an obscure possibility, but if the tableName variable were to contain this string or something like it:
Table1 set foo = 'bar';
truncate table ba2;
update table3
You could see how it would compile, execute and do something other than what you had in mind. Again, I realize this is reaching, and your input does come from a combo box, but it's still a theoretical risk.

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();

SQL code for delete Row?

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 ;)

Categories