Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a value to Sql CommandText

Nowadays I am programming a cricket scoring software and all the details are saved in a database. I want to know how to add +1 to the field "W" in the database when click "Wicket".

cmd.CommandText = "UPDATE database.table SET W=W+1 WHERE bowler='" & frmmain.lblbowler.Text & "' "

In this code frmmain.lblbowler.text contains the bowler name.

Is this code correct? What changes must do? Please be kind enough to answer.

like image 925
Pasindu Jayaneth Avatar asked Mar 03 '26 03:03

Pasindu Jayaneth


1 Answers

Don’t ever build a query this way! The input frmmain.lblbowler.Text is typically retrieved from a TextBox control on either a Windows form or a Web Page. Anything placed into that TextBox control will be put into frmmain.lblbowler.Text and added to your SQL string. This situation invites a hacker to replace that string with something malicious. In the worst case, you could give full control of your computer away.

Instead of dynamically building a string, as shown in your code, use parameters.

Anything placed into a parameter will be treated as field data, not part of the SQL statement, which makes your application much more secure.

Try the following

cmd.CommandText = "UPDATE database.table SET W=W+1 WHERE bowler = @bowler"

command.Parameters.Add("@bowler", SqlDbType.NVarChar)
command.Parameters("@bowler").Value =  frmmain.lblbowler.Text
like image 118
Hadi Avatar answered Mar 06 '26 00:03

Hadi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!