310 CHAPTER 8 WRITING TO THE DATABASE INSERT Player (PlayerName, PlayerManufacturerID, PlayerCost, PlayerStorage) VALUES (@Name, @ManufacturerID, @Cost, @Storage); SELECT SCOPE_IDENTITY(); When sending a query to a SQL Server 2005 database, you can actually send multiple queries, separated by semicolons. You want to insert the Player into the database, but you also want to know the PlayerID of the Player that you ve added. In this example, you display the PlayerID as a confirmation that the Player has been added to the database. In the next example, you ll use this PlayerID when adding the details of the Formats that the Player supports. When using a column defined as an identity column, you can use the SCOPE_IDENTITY() function to retrieve the value of that column. In order to return the value from this function, you can use it as a column in a SELECT query. Note The system variable @@IDENTITY returns the value of the identity column last entered. In this instance, both the SCOPE_IDENTITY() function and the @@IDENTITY system variable would return the same value. However, in cases when you re using triggers, the @@IDENTITY system variable may return the wrong value; if the trigger also does an INSERT, it may return the identity value from a different table, whereas the SCOPE_IDENTITY() function returns the identity value from the original table. You should always use the SCOPE_IDENTITY() function to prevent any problems if triggers are added to your tables later. Thus, when you execute this query, you do so by calling ExecuteScalar() rather than ExecuteNonQuery() so you can capture the new PlayerID. ExecuteScalar() returns a generic object, rather than a string or an integer, so you cast it to an integer to make it easier to handle: // execute the query intPlayerID = Convert.ToInt32(myCommand.ExecuteScalar()); If there was an error when inserting the Player, an exception is thrown. You catch this and set the PlayerID to -1 to indicate that the INSERT query failed: catch { // return -1 to indicate error intPlayerID = -1; } Although all you re doing here is setting a flag to indicate that there has been an error, you re free to perform any other actions you want. If you want to send an e-mail message to the Web site administrator informing her that a problem has occurred, you can do so. Just be careful that your error-handling code doesn t throw an exception, as that would cause a runtime error to be displayed to the user! Once you ve executed the query and returned the PlayerID, you exit from the SavePlayer() method and either display an error message or a confirmation to the user. At this point, the user can return to the list of Players to confirm that the new Player has been added and to add another Player if desired.
From our experience, we can recommend PHP5 Web Hosting services, if you need affordable webhost to host and run your web application.