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!!)
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:
Now you’ve associated your
UPDATEstatement with theSqlDataAdapter.UpdateCommandand 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:
and then before you execute the command or the
SqlDataAdapter.Updatestatement, 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
SqlDataAdapterat all??After you’ve created the
SqlCommandand set all the parameters, just callcmd.ExecuteNonQuery();and you’re done!