3

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.

Yahfoufi
  • 2,220
  • 1
  • 22
  • 41
  • The code looks correct. Did you get an error? – Madhivanan Jul 26 '16 at 05:55
  • We don't know the structure of your database but I think it is correct. What is your question again? Just check the query or advice about connecting to SQL database? – DangeMask Jul 26 '16 at 05:56
  • It's not appropriate to come here and ask us if your code is correct. You need to run the code and if it works then you know it's correct and only if it doesn't do you post a question here and provide us with all the relevant information, e.g. error messages. – jmcilhinney Jul 26 '16 at 06:08
  • 1
    Also, you should learn how to use parameters in your ADO.NET code. Steve O'Keefe dismissed Angelo Mathews not long ago in the current Aust/SL Test and your app would crash if it was scoring that game. – jmcilhinney Jul 26 '16 at 06:10
  • @jmcilhinney Can I add parameters instead of frmmain.lblbowler.text – Pasindu Jayaneth Jul 26 '16 at 06:30
  • No you can't, and some research on the subject would reveal that that's a nonsensical question. Check out my blog post on the subject. http://jmcilhinney.blogspot.com.au/2009/08/using-parameters-in-adonet.html – jmcilhinney Jul 26 '16 at 07:05
  • Related: http://stackoverflow.com/q/35163361/87698 – Heinzi Dec 12 '16 at 13:56

1 Answers1

1

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
Hadi
  • 36,233
  • 13
  • 65
  • 124