Increment a database value using asp.net - asp.net

I am working on a project - online movie ticketing system....
In this when the user enters the number of seats he wants to book, he goes to payment page. On click of payment button, how can I decrement the number of seats entered by the user in SQL Server.
SqlConnection con;
SqlCommand cmd;
private void update()
{
string a, b;
int c;
con = new SqlConnection("server=.;uid=sa;pwd=mayank;database=movie");
a = Session["timings"].ToString();
b = Session["seats"].ToString();
c = Convert.ToInt32(b);
con.Open();
cmd = new SqlCommand("update bodyguard set silver_class = silver_class ' " + - c + " 'where timings = ' " + a + "' ", con);
cmd.ExecuteNonQuery();
con.Close();
}
With this code it is raising an exception....so please help me out.

Your SQL command is wrong, what you produce is this:
update bodyguard set silver_class = silver_class ' -[valueC] 'where timings = ' [valueA]'
You forgot a space before where for example, and I am not sure how the silver_class part is supposed to look, because it's not clear what you are trying to achieve there.

You had some single quotes around your integer value. try this
"update bodyguard set silver_class = (silver_class - " + c + ") where timings = '" + a + "'"
A little advice, you should use a try{}catch{} blocks to handle potential errors in your code. When you convert a number with Convert.toInt32(), you should try to catch a FormatException. And from con.open() to con.close you can try to catch the SQLException

Don't use concatenated strings to create your SQL statment, its really bad form. Do it this way:
cmd = new SqlCommand("update bodyguard set silver_class = silver_class - #c where timings = #a", con);
cmd.Parameters.AddWithValue("#c", c);
cmd.Parameters.AddWithValue( "#", a);

I recommend Parameterized Query instead of string concatenation which is vulnerable to SQL Injection. And I suggest that you should use Stored Procedure instead of Inline SQL.

Related

asp.net SQL SUM clause with join on another table syntax error

I am developing a gridview fill on asp.net web forms and thought the SQL statement would have similar syntax compared to mysql.
I have a CustomerList and CustomerTracking table where CustomerTracking has a CustUUID that links to the CustomerList table entries. I am also trying to get the SUM of all entries that match the CustUUID from banner in CustomerTracking
Here is the sql statement I am trying to parse.
string command2 = "SELECT b.Name, b.Link, SUM(t.CustomerTracking) as CustomerTrackingList, SUM(t.ClickCount) as ClickCount " +
"FROM CustomerList as b JOIN CustomerTracking as t" +
"IN b.CustUUID= t.CustUUID" +
"WHERE t.date> 11/21/2006";
Have also tried explicitly stating the table names as follows.
string command2 = "SELECT CustomerList.Name, CustomerList.Link, SUM(CustomerTrackingList.CustomerTracking) CustomerTracking, SUM(CustomerTrackingList.ClickCount) ClickCount " +
"FROM CustomerList JOIN CustomerTrackingList" +
"ON CustomerList.CustUUID = CustomerTracking.CustUUID" +
"WHERE CustomerTracking.date> 11/21/2006";
I keep getting sytax errors when I try and invoke sda.fill(dt) in the code behind file below. Is the syntax correct or am I missing some decorators that asp.net is looking for?
This is the error Visual Studio is showing me!
System.Data.SqlClient.SqlException: 'Incorrect syntax near '.'.'
using (SqlCommand cmd = new SqlCommand(command2))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView2.DataSource = dt;
GridView2.DataBind();
}
}
}
You don't even provide the error, however I can immediately see your date is not quoted, it should be
WHERE t.CreateDate > '11/21/2006'
and I would suggest always to use ISO dates eg '20061121'
And if you actually build your string you will be sending this to SQLServer
SELECT b.Name, b.Link, SUM(t.ImpressionCount) as ImpressionCount, SUM(t.ClickCount) as ClickCount FROM Banner as b JOIN BannerTracking as **tIN** b.BannerId = **t.BannerIdWHERE** t.CreateDate > 11/21/2006
Added -
Make sure you add white space at the end of each section to ensure it gets parsed correctly.

Insert into SQL Server table gives me nothing

Very frustrating one... I have tried many combinations of ', " and so on but my insert command just refreshing the page.
What am I doing wrong?
Simple two text fields form with button. Under button I have this:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["przychodniaConnectionString1"].ConnectionString);
con.Open();
string cmdStr = "INSERT INTO specyfik(speNazwa, speIlosc) values ('" + speNazwa.Text + "', '" + speIlosc.Text + "')";
SqlCommand insertCmd = new SqlCommand(cmdStr, con);
con.Close();
Zero errors while compiling and when testing, it seems like refreshed page. Nothing appears in db.
Don't you need to call insertCmd.ExecuteNonQuery() ?
...
SqlCommand insertCmd = new SqlCommand(cmdStr, con);
int row_affected = insertCmd.ExecuteNonQuery();
...
You need to execute your SqlCommand:
insertCmd.ExecuteNonQuery();
Also, you should look into parameterizing that query:
http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html
Will you like to make more improvements in your code using stored Proc and improvemnet in your code behind file ? Take a look at this answer...
https://stackoverflow.com/a/9595501/1209450

asp.net Login Website from database

I have a website with a login, from a database.
This is my code :
protected void SignIn_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Movie;Integrated Security=True");
con.Open();
string cmdStr = "select count(*) from Users";
cmdStr += "where Username='" + UsernameSignIn.Text + "'";
cmdStr+= "AND Password='"+PasswordSignIn.Text+"'";
SqlCommand cmd = new SqlCommand(cmdStr, con);
int i = Convert.ToInt16(cmd.ExecuteScalar());
if (i == 0)
{
ErrorSignIn.Text = "Sorry, Wrong Username or Password";
}
else
{
Response.Redirect("HomeAfter.aspx");
}
}
for some reason, I run into an error :
Incorrect syntax near '-'
.
(for this line : int i = Convert.ToInt16(cmd.ExecuteScalar()); )
Thanks,
There is no spacing. Your query looks like this:
select count(*) from Userswhere Username='...'AND Password='...'
Add spaces, like so:
string cmdStr = "select count(*) from Users";
cmdStr += " where Username='" + UsernameSignIn.Text + "'";
cmdStr+= " AND Password='"+PasswordSignIn.Text+"'";
Aside from the fact that this is particularly crude as a form of authentication (you really ought to consider using the built-in ASP.NET Membership provider(s)) you should at a minimum be using parameterized SQL queries, rather than concatenating plain text to create your SQL statement. Also, I notice that your "login" arrangement simply does a response.redirect to the HomeAfter.aspx page without storing anything to be re-used that will indicate the user has already successfully logged in, such as a cookie or a sesssion variable.
Is there any particular reason for all this, or is it because you're just starting out and you need to study up a bit?

why this code enter two entries into the database

i have a code that retrieve some content and enter it the database :
MySqlConnection conn = new MySqlConnection(#"connection string");
MySqlCommand cmd = new MySqlCommand("INSERT INTO copy (id) VALUES ('" + Page.User.Identity.Name + "')", conn);
MySqlCommand cmd2 = new MySqlCommand("INSERT INTO copy (cv) VALUES ('" + mainEditor.Content.Replace("'", "''") + "')",conn);
conn.Open();
cmd.ExecuteNonQuery();
cmd2.ExecuteNonQuery();
conn.Close();
it connects and enters the data fine but it enters the data in two not one (it creates two rows instead of one)
i am using asp.net 3.5 and mysql 5.0
what am i doing wrong, thanks.
It's inserting two rows because you're executing two INSERT statements. Each time you run an INSERT it does just that: inserts a row.
I'm guessing you wanted to create a single row with both the id and cv fields populated. The SQL syntax for that is INSERT INTO copy (id, cv) VALUES ('x', 'y');
So:
MySqlCommand cmd = new MySqlCommand("INSERT INTO copy (id) VALUES ('" + Page.User.Identity.Name + "', '" + mainEditor.Content.Replace("'", "''") + "')",conn);
It's because two separate inserts are running. You can insert more than one value, try this:
MySqlCommand cmd = new MySqlCommand("INSERT INTO copy (id, cv) VALUES ('" + Page.User.Identity.Name + "', '" + mainEditor.Content.Replace("'", "''") + "')", conn);
You can comma separate the fields, and the values so it inserts into one record. Executing 2 insert commands will always create 2 records.
You didn't say which driver you're using so I'll use the documentation I found for dotConnect. I would try to use something along these lines (explanation of code below)
using( var conn = new MySqlConnection(#"connection string"))
using( cmd = new MySqlCommand("", conn) ){
cmd.CommandText = #"
INSERT INTO copy (id, cv)
VALUES (:name, :userContent)";
cmd.Parameters.Add("name", MySqlType.[correct type]]).Value = Page.User.Identity.Name;
cmd.Parameters.Add("userContent", MySqlType.[correct type], [column size]).Value = mainEditor.Content;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
The use of the using construct is because MySqlConnection and MySqlCommand classes both implement the IDisposable interface so they need to be disposed of when you're done using them to avoid possible resource leaks.
The :name and :userContent is what I found in documentation for creating parametrized queries. This will allow the database driver to take care of escaping all of the special characters out of user input to avoid SQL injection attacks. This part is actually really important, there are some REALLY sophisticated SQL injection attacks out there, so there's a good chance simply escaping ' (as you were doing) isn't enough.

Web form is not updating tables, why?

I have a web application and on page is an update page to update some profile information. Below is the code I am using to update the table. But I think it is wrong. Does anything stick out? The connection string works cause it is used to read the database to get the profile information, I just removed it due to it containing password/login info for the db.
player is the class of properties that contains player information and ds is the dataset, but I would like to update the database itself online...
Dim connectionString As String = ""
Dim GigsterDBConnection As New System.Data.SqlClient.SqlConnection(connectionString)
GigsterDBConnection.Open()
Dim updatetoursql As String = "UPDATE PLAYERS SET FIRSTNAME = '" & player.FIRSTNAME & "', LASTNAME = '" & player.LASTNAME & "', ADDRESS = '" & player.ADDRESS & "', CITY = '" & player.CITY & "', ZIP = '" & player.ZIP & "', PHONE = '" & player.PHONE & "', EMAIL = '" & player.EMAIL & "', REFFEREDBY = '" & player.REFEREDBY & "' "
updatetoursql = updatetoursql & "PLAYERID = '" & player.PLAYERID & "';"
Dim cmd As New System.Data.SqlClient.SqlCommand(updatetoursql, GigsterDBConnection)
Dim sqlAdapter As New System.Data.SqlClient.SqlDataAdapter(cmd)
sqlAdapter.Update(ds, "PLAYERS")
I think the issue is something the 3 last lines of the code. am I doing it right or is their a better way?
Thanks
Well, apart from the glaring SQL injection issues waiting to bite you ..... (hint: use parametrized queries instead of concatenating together your SQL statement!!)
Dim cmd As New SqlCommand(updatetoursql, GigsterDBConnection)
Dim sqlAdapter As New SqlDataAdapter(cmd)
The problem here is: if you call the SqlDataAdapter constructor this way, what you're passing in is the select command (of the data adapter) - not the update command!
You need to do it this way:
Dim cmd As New SqlCommand(updatetoursql, GigsterDBConnection)
Dim sqlAdapter As New SqlDataAdapter()
sqlAdapter.UpdateCommand = cmd;
Now you've associated your UPDATE statement with the SqlDataAdapter.UpdateCommand and now it should work.
About the SQL injection: I'd strongly recommend using parametrized queries all the time - at least in production code. So instead of concatenating together your query, use this:
Dim updatetoursql As String =
"UPDATE PLAYERS SET FIRSTNAME = #FirstName, LASTNAME = #LastName, " &
"ADDRESS = #Address, CITY = #City, ZIP = #Zip, PHONE = #Phone " &
"EMAIL = #EMail, REFFEREDBY = #ReferredBy, PLAYERID = #PlayerID"
and then before you execute the command or the SqlDataAdapter.Update statement, set those parameters to the values you have. This is much safer and gives you less headaches and possibly even speed improvements (if that single Update query is only cached once in SQL Server memory).
Also, why go the long and complicated way of a SqlDataAdapter at all??
After you've created the SqlCommand and set all the parameters, just call cmd.ExecuteNonQuery(); and you're done!
Dim cmd As New SqlCommand(updatetoursql, GigsterDBConnection)
// set up the parameters here.....
cmd.Parameters.AddWithvalue("#FirstName", FirstName);
... etc.
// just call ExecuteNonQuery - and you're done!
cmd.ExecuteNonQuery();
The big thing that jumps up at me is how open to SQL Injection attacks this code is.
You should not build a SQL string in this manner, but use parameterized queries.
Other then that, you are constructing your adapter incorrectly, as the constructor will take the select command, not the update command. Create the command with the parameterless constructor then assign the command you have created to the UpdateCommand property.

Resources