Web-based Programming Lanjut Pertemuan 7 Matakuliah : M0492 / Web-based Programming Lanjut Tahun : 2007
Dec 20, 2015
Web-based Programming Lanjut Pertemuan 7
Matakuliah : M0492 / Web-based Programming Lanjut Tahun : 2007
Bina Nusantara
Connection, Command dan Procedure
• The Connection Object• The Command Object• Stored Procedure• Optimization• Data Shaping
Bina Nusantara
The Connection Object
• Connection object– Gives us connection to the data store– Run the commands
• action queries (updates, inserts, deletes)• return a recordset
• Returning a RecordsetTo return a recordset use the ‘Execute’ methodThe syntax is:
Connection.Execute CommandText, [RecordsAffected], [Options]
Bina Nusantara
The Connection Object
Argument Description
CommandText The text of the command to execute. This is the same as the ‘Source’ of the Recordset ‘Open’ method, and can also represent an existing Command object.
RecordsAffected A variable into which is placed the number of records affected by the command.
Options The command options, which can be one or more of the values from the CommandTypeEnum or ExecuteOptionEnum constants, as detailed in session 6.
Set conPubs = Server.CreateObject(“ADODB.Connection”)
conPubs.Open strConn
Set rsAuthors = conPubs.Execute (“Authors”)
The difference between Execute and Open method:
• Open method have the ability to change the cursor type and lock type
• Execute method always get a forward-only cursor and read-only recordset.
Bina Nusantara
The Connection Object• Action Commands
You can use the RecordsAffected argument to find out how many records were affected by the command.
• No Recordset ReturnedIf no recordset is being returned, then it’s also best to add another option to the Execute statement :
Dim strSQL as StringDim lngRecs as Long
strSQL = “UPDATE Titles SET Price = Price * 1.10 WHERE Type=‘Business’”
conPubs.Execute strSQL, lngRecs, adCmdText
Response.Write lngRecs & “ records were updated.”
conPubs.Execute strSQL, lngRecs, adCmdText + adExecuteNoRecords
Bina Nusantara
The Command Object
• Command Object– Deal with commands of any sort, especially that require parameters.– Can run both commands that return recordsets and not return
recordsets.– If your command doesn’t have parameters, then it doesn’t matter
whether you use a Connection, a Command, or a Recordset.
• Returning Recordsets– use the Execute method and the CommandText property.
Set cmdAuthors = Server.CreateObject(“ADODB.Command”)
cmdAuthors.CommandText = “Authors”
Set rsAuthors = cmdAuthors.Execute
Bina Nusantara
The Command Object
The Execute method also has some optional arguments:
Argument Description
RecordsAffected A variable into which is placed the number of records affected by the command.
Parameters An array of parameter values.
Options The command options. This is similar to the ‘Options’ of the Recordset ‘Open’ method.
Set cmdAuthors = Server.CreateObject(“ADODB.Command”)cmdAuthors.CommandText = “Authors”cmdAuthors.CommandType = adCmdTableSet rsAuthors = cmdAuthors.Execute
Or
Set rsAuthors = cmdAuthors.Execute (, , adCmdTable)
Bina Nusantara
The Command Object
• Changing the Cursor TypeIf require a different cursor or lock type, use the Open method.
• Action CommandFor action commands, such as update data without returning any records:
cmdAuthors.ActiveConnection = strConn
cmdAuthors.CommandText = “Authors”
cmdAuthors.CommandType = adCmdTable
rsAuthors.Open cmdAuthors, , adOpenDynamic, adLockOptimistic
Set cmdUpdate = Server.CreateObject(“ADODB.Command”)
StrSQL = “UPDATE Titles SET Price = Proce * 1.10 WHERE Type = ‘Business’”
cmdUpdate.ActiveConnection = strConn
cmdUpdate.CommandText = strSQL
cmdUpdate.CommandType = adCmdText
cmdUpdate.Execute , , adExecuteNoRecords
Bina Nusantara
Stored Procedures
• A stored procedures (stored query) is a predefined SQL query stored on the database.
• The reasons why we create and use a stored procedure:– Compiled by database. Produces an execution plan, so the database knows
exactly what it’s going to do. This makes the execution of the procedure faster.
– Stored procedures are often cached by the database, thus making them faster to run. Not all databases support this caching mechanism – Microsoft Access doesn’t, but SQL Server does.
– More secure by specifying that your database tables can be modified only by stored procedures.
– Avoid cluttering ASP code with lengthy SQL statements. This makes the ASP code easier to maintain.
– Keep all the SQL code together, on the server.
– Can use output parameters, which allows to return both a recordset and other values.
Bina Nusantara
Stored Procedures
CREATE PROCEDURE usp_UpdatePrices
AS
UPDATE Titles
SET Price = Price * 1.10
WHERE Type = ‘Business’
A stored procedure on SQL Server
For a Microsoft Access database, you can create a simple update query to do the same task
Bina Nusantara
Stored Procedures
• To run this stored procedure from an ASP page, you’d simply use the following code:
Set cmdUpdate = Server.CreateObject (“ADODB.COmmand”)
cmdUpdate.ActiveConnection = strConn
cmdUpdate.CommandText = “usp_UpdatePrices”
cmdUpdate.CommandType = adCmdStoredProc
cmdUpdate.Execute , , adExecuteNoRecords
Bina Nusantara
Stored Procedures• Parameters
Must follow the naming convention for SQL variables, which means they must start with an @ symbol.
CREATE PROCEDURE usp_UpdatePrices
@Type Char(12),
@Percent Money
AS
UPDATE Titles
SET Price = Price * ( 1 + @Percent / 100 )
WHERE Type = @Type
Bina Nusantara
Stored Procedures• The Parameters Collection
Set Parameter = Command.CreateParameter (Name, [Type], [Direction], [Size], [Value])
Argument Description
Name The name of the parameter. This isn’t the name of the parameter in the stored procedure, but the name of the parameter in the Parameters collection. It is however, a good idea to use the same names.
Type The data type of the parameter. This can be one of the adDataType constants, which are detailed in the appendices.
Direction The direction of the parameter, indicating whether the parameter supplies information to the stored procedure, or whether the procedure supplies the information back to ADO. The value can be one of:• adParamInput (1), is an input parameter, being sent to the stored procedure.• adParamOutput (2), is an output parameter, being retrieved from the stored procedure.• adParamInputOutput (3), is both an input and an output parameter.• adParamReturnValue (4), holds the return status of the stored procedure.
Size The size of the parameter. For fixed length types, such as numbers, this can be omitted.
Value The value of the parameter.
Bina Nusantara
Stored Procedures• Once the parameter is created it can be appended to the
Parameters collection.Set parValue = cmdUpdate.CreateParameter (“@Type”, adVarWChar, adParamInput, 12, “Business”)
cmdUpdate.Parameters.Append parValue
Set parValue = cmdUpdate.CreateParameter (“@Percent”, adCurrency, adParamInput, ,10)
cmdUpdate.Parameters.Append parValue
cmdUpdate.Parameters(“@Percent”) = 10
If you don’t want to create a variable, you can also take a shortcut :cmdUpdate.Parameters.Append = _
cmdUpdate.CreateParameter (“@Type”, adVarWChar, adParamInput, 12, “Business”)
cmdUpdate.Parameters.Append = _
cmdUpdate.CreateParameter (“@Percent”, adCurrency, adParamInput, ,10)
cmdUpdate.Parameters(“@Percent”) = 10
The Parameters in the Parameters collection must match the order of the parameters in the stored procedure.
Bina Nusantara
Stored Procedures1. <HTML><HEAD><TITLE>Stored Procedure with Parameter</TITLE></HEAD><!-- UpdatePrices.asp -->2. <BODY>3. <!-- #include file="dataconn.inc" -->4. <FORM NAME="UpdatePrices" Method="Post" ACTION="StoredProcedure.asp">5. <TABLE>6. <TR><TD>Book Type:</TD>7. <TD><SELECT NAME="lstTypes">8. <%9. Dim rsTypes10. Dim strSQL11. Dim strQuote
12. strQuote = Chr(34) 'Predefined the quote character13. Set rsTypes = Server.CreateObject("ADODB.Recordset")14. strSQL = "SELECT DISTINCT type FROM titles"15. rsTypes.Open strSQL, Conn
16. While Not rsTypes.EOF17. Response.Write "<OPTION VALUE=" & strQuote & rsTypes("Type") & strQuote & ">" & rsTypes("Type")18. rsTypes.MoveNext19. Wend
20. rsTypes.Close21. Set rsTypes = Nothing22. %></SELECT></TD></TR>23. <TR><TD>Percent Value</TD>24. <TD><INPUT NAME="txtPercent" TYPE="TEXT"></TD></TR>25. </TABLE>26. <P><INPUT TYPE="Submit" VALUE="Run Query">27. </FORM></BODY></HTML>
Bina Nusantara
Stored Procedures1. <!-- #include file="dataconn.inc" -->2. <!-- StoredProcedure.asp -->3. <%4. Dim cmdUpdate5. Dim lngRecs6. Dim strType7. Dim curPercent
8. 'get from the values9. strType = Request.Form("lstTypes")10. curPercent = Request.Form("txtPercent")
11. 'Tell the user what's being done12. Response.Write "Updating all books of type <B>" & strType & "</B> by " & curPercent & "%<P>"
13. Set cmdUpdate = Server.CreateObject("ADODB.Command")
14. ' Set the properties of the command15. With cmdUpdate16. .ActiveConnection = conn17. .CommandText = "usp_UpdatePrices"18. .CommandType = 4 ‘adCmdStoredProc = 419. .Parameters.Append .CreateParameter("@Type", 202, 1, 12, strType) ‘adVarWChar = 202, adParamInput=120. .Parameters.Append .CreateParameter("@Percent", 6, 1,, curPercent) ‘adCurrency = 621. .Execute lngRecs,,128 ‘adExecuteNoRecords=12822. End With
23. 'And finally tell the user what's happened24. Response.Write "Procedure complete. " & lngRecs & " records were updated."25. Set cmdUpdate = Nothing26. %>
Bina Nusantara
Stored Procedures
Bina Nusantara
Stored Procedures• Passing Parameters as an Array
Utilizes the Array function, which turns individual variables into an array, suitable for passing into this method call.Some disadvantages to this method:– You can only use input parameters.– This method is slower if you intend to call the stored
procedure several times, since ADO will ask the data store what parameters are, and what data types they use.
Set cmdUpdate = Server.CreateObject(“ADODB.Command”)With cmdUpdate
.ActiveConnection = conn
.CommandText = “usp_UpdatePrices”
.CommandType = adCmdStoredProc‘Execute the command.Execute lngRecs, Array(strType, curPercent), adExecuteNoRecords
End With
Bina Nusantara
Stored Procedures
• Output ParametersIf you want more information, but still don’t want to return a recordset, you can define a parameter as an output parameter.CREATE PROCEDURE usp_UpdatePricesMax
@Type Char(12),@Percent Money,@Max Money OUTPUT
ASUPDATE TitlesSET Price = Price * ( 1 + @Percent / 100 )WHERE Type = @Type
SELECT @Max = MAX(Price)FROM Titles
Bina Nusantara
Stored Procedures1. <!-- #include file="dataconn.inc" --> <!-- StoredProcedureMax.asp -->2. <%3. Dim cmdUpdate4. Dim lngRecs5. Dim strType6. Dim curPercent7. Dim curMax8. 'get from the values9. strType = Request.Form("lstTypes")10. curPercent = Request.Form("txtPercent")
11. 'Tell the user what's being done12. Response.Write "Updating all books of type <B>" & strType & "</B> by " & curPercent & "%<P>"
13. Set cmdUpdate = Server.CreateObject("ADODB.Command")14. ' Set the properties of the command15. With cmdUpdate16. .ActiveConnection = conn17. .CommandText = "usp_UpdatePricesMax"18. .CommandType = 4 ‘adCmdStoredProc = 419. .Parameters.Append .CreateParameter("@Type", 202, 1, 12, strType) ‘adVarWChar = 202, adParamInput=120. .Parameters.Append .CreateParameter("@Percent", 6, 1,, curPercent) ‘adCurrency = 621. .Parameters.Append .CreateParameter("@Max", 6, 2) ‘adCurrency = 6, adParamOutput=222. .Execute lngRecs,,128 ‘adExecuteNoRecords=12823. curmax = .Parameters(“@Max”) ‘Extract the OUTPUT parameter24. End With25. 'And finally tell the user what's happened26. Response.Write "Procedure complete. " & lngRecs & " records were updated.“27. Response.Write "The highest price book is now " & FormatCurrency(curMax)28. Set cmdUpdate = Nothing29. %>
Bina Nusantara
Stored Procedures
Bina Nusantara
Stored Procedures• Return Values
– Return values from functions are handled differently from the way return values from stored procedures.
– In user functions, we often return a Boolean value to indicate the success or failure of a function
– When calling a stored procedure though, we can’t use the same method. The stored procedure are run using the Execute method, and this returns a recordset.
For example, consider adding a new employee to the employee table. You don’t want to stop two people with the same name being added, but you might want this situation flagged. Here we can use a return value, to indicate whether an employee wuth the same name already exists.
Bina Nusantara
Stored ProceduresCREATE PROCEDURE usp_AddEmployee
@Emp_ID Char(9),@FName Varchar(20),@MInit Char(1),@LName Varchar(30),@Job_Id SmallInt,@Job_Lvl TinyInt,@Pub_ID Char(4),@Hire_Date Datetime
ASBEGIN
DECLARE @Exists Int -- Return Value
-- See if an employee with the same name existsIF EXISTS (SELECT *
FROM EmployeeWHERE FName = @FNameAND MInit = @MInitAND LName = @LName)
SELECT @Exists = 1ELSE SELECT @Exists = 0
INSERT INTO Employee (emp_id, fname, minit, lname, job_id, job_lvl, pub_id, hire_date) VALUES (@Emp_ID, @FName, @MInit, @LName, @Job_Id, @Job_Lvl, @Pub_ID, @Hire_Date)
RETURN @ExistsENDGO
Bina Nusantara
Stored Procedures1. <HTML><HEAD><TITLE>Stored Procedure with Return Values</TITLE></HEAD><!-- ReturnValues.asp -->2. <BODY><!-- #include file="dataconn.inc" -->3. <H1>Retuen Values from stored procedures<HR></H1>4. <FORM NAME="ReturnValues" Method="Post" ACTION="StoredProcedureAdd.asp">5. <TABLE>6. <TR><TD>Employee ID:</TD> <TD><INPUT NAME="txtEmp_ID" TYPE="TEXT"></TD></TR>7. <TR><TD>First Name:</TD> <TD><INPUT NAME="txtFName" TYPE="TEXT"></TD></TR>8. <TR><TD>Initial:</TD> <TD><INPUT NAME="txtMInit" TYPE="TEXT"></TD></TR>9. <TR><TD>Last Name:</TD> <TD><INPUT NAME="txtLName" TYPE="TEXT"></TD></TR>10. <TR><TD>Job:</TD><TD><SELECT NAME="lstJob">11. <%12. Dim rsJobs13. Dim strSQL14. Dim strQuote
15. strQuote = Chr(34) 'Predefined the quote character16. Set rsJobs = Server.CreateObject("ADODB.Recordset")17. strSQL = "SELECT DISTINCT job_id, job_desc FROM jobs"18. rsJobs.Open strSQL, Conn
19. While Not rsJobs.EOF20. Response.Write "<OPTION VALUE=" & strQuote & _21. rsJobs("job_id") & strQuote & ">" & rsJobs("job_desc")22. rsJobs.MoveNext23. Wend
24. rsJobs.Close25. Set rsJobs = Nothing26. %></SELECT></TD></TR>
Bina Nusantara
Stored Procedures27. <TR><TD>Job Level: </TD><TD><INPUT NAME="txtJob_Lvl" TYPE="TEXT"></TD></TR>28. <TR><TD>Publisher: </TD><TD><SELECT NAME="lstPub">29. <%30. Dim rsPub
31. Set rsPub = Server.CreateObject("ADODB.Recordset")32. strSQL = "SELECT DISTINCT pub_id, pub_name FROM publishers"33. rsPub.Open strSQL, Conn
34. While Not rsPub.EOF35. Response.Write "<OPTION VALUE=" & strQuote & _36. rsPub("pub_id") & strQuote & ">" & rsPub("pub_name")37. rsPub.MoveNext38. Wend
39. rsPub.Close40. Set rsPub = Nothing41. %></SELECT></TD></TR>42. <TR><TD>Hire Date: </TD>43. <TD><INPUT NAME="txtHire_Date" TYPE="TEXT" Value="<%= FormatDateTime(date()) %>"></TD>44. </TR>45. </TABLE>46. <P>47. <INPUT TYPE="Submit" VALUE="Run Query">48. </FORM>49. </BODY>50. </HTML>
Bina Nusantara
Stored Procedures
Bina Nusantara
1. <!-- #include file="dataconn.inc" --><!-- StoredProcedureAdd.asp -->2. <% Dim cmdEmployee3. Dim lngRecs4. Dim lngAdded5. Set cmdEmployee = Server.CreateObject("ADODB.Command")6. With cmdEmployee7. .ActiveConnection = conn8. .CommandText = "usp_AddEmployee"9. .CommandType = 4
10. .Parameters.Append .CreateParameter("RETURN_VALUE", 3, 4)11. .Parameters.Append .CreateParameter("@Emp_ID", 129, 1, 9)12. .Parameters.Append .CreateParameter("@FName", 202, 1,20)13. .Parameters.Append .CreateParameter("@MInit", 129, 1, 1)14. .Parameters.Append .CreateParameter("@LName", 202, 1,30)15. .Parameters.Append .CreateParameter("@Job_Id", 2, 1)16. .Parameters.Append .CreateParameter("@Job_Lvl", 17, 1)17. .Parameters.Append .CreateParameter("@Pub_ID", 129, 1, 4)18. .Parameters.Append .CreateParameter("@Hire_Date", 135, 1,8)
19. .Parameters("@Emp_ID") = Request.Form("txtEmp_ID")20. .Parameters("@FName") = Request.Form("txtFName")21. .Parameters("@MInit") = Request.Form("txtMInit")22. .Parameters("@LName") = Request.Form("txtLName")23. .Parameters("@Job_Id") = Request.Form("lstJob")24. .Parameters("@Job_Lvl") = Request.Form("txtJob_Lvl")25. .Parameters("@Pub_ID") = Request.Form("lstPub")26. .Parameters("@Hire_Date") = Request.Form("txtHire_Date")
27. .Execute lngRecs,,12828. lngAdded = .Parameters("RETURN_VALUE")29. End With30. Response.Write "New Employee added.<P> "31. If lngAdded = 1 Then32. Response.Write "An Employee with the same name already exists."33. End If34. Set cmdEmployee = Nothing35. %>
Bina Nusantara
Stored Procedures
Bina Nusantara
Stored Procedures• Refreshing Parameters
Instead of typing in all of the parameter details yourself, ADO can do it for you, simply by calling the Refresh method .
But be aware that it imposes a performance penalty, since ADO must query the provider for the details of the parameters for the stored procedure.
1. With cmdEmployee2. .ActiveConnection = conn3. .CommandText = "usp_AddEmployee"4. .CommandType = 4
5. .Parameters.Refresh
6. .Parameters("@Emp_ID") = Request.Form("txtEmp_ID")7. .Parameters("@FName") = Request.Form("txtFName")8. .Parameters("@MInit") = Request.Form("txtMInit")9. .Parameters("@LName") = Request.Form("txtLName")10. .Parameters("@Job_Id") = Request.Form("lstJob")11. .Parameters("@Job_Lvl") = Request.Form("txtJob_Lvl")12. .Parameters("@Pub_ID") = Request.Form("lstPub")13. .Parameters("@Hire_Date") = Request.Form("txtHire_Date")
14. .Execute lngRecs,,12815. lngAdded = .Parameters("RETURN_VALUE")16. End With
Bina Nusantara
Optimization
• General ADO Tips– Pick only the columns you need– Use stored procedures as much as possible– Use stored procedures for data changes– Don’t create a recordset unless it’s required– Use the appropriate cursor and lock modes
• Object Variables– One guaranteed way to improve performance whilst
looping through recordset is to use object variables
Bina Nusantara
Optimization• Cache Size
– Cache size is the number of records that ADO reads at a time from the data sore, and it defaults to 1.
– The size 1 means, every time you move to another record, the record must be fetched from the data store.
– Increasing the size of the cache to 10, for example, would mean that records are read into the ADO buffer 10 at a time.
– Set the size of the cache by using the CacheSize property :rsAuthors.CacheSize = 10
Bina Nusantara
Data Shaping
• Allows to represent a tree-like structure or related recordset.
• Reasons why this is useful:– Performance : When used correctly, data shaping can
improve performance– Convenience : It’s extremely easy to map the parent/child
relationship in data shaping.
• Using data shaping– Use the MSDataShape OLEDB Provider– Use a special Shape language, a superset of SQL, that
allows you to construct the hierarchies
Bina Nusantara
Data Shaping• The Connection String
• The Shape Language
SHAPE {parent command} [AS parent alias]APPEND ({child command} [AS child alias]RELATE parent_column TO child_column) [AS parent_column_name]
For Example:
SHAPE {SELECT * FROM Publishers } APPEND ({SELECT * FROM Titles}RELATE Pub_ID TO Pub_ID) AS rsTitles
Provider=MSDataShape; Data Provider = SQLOLEDB; Data Source=…
Bina Nusantara
Data Shaping1. <!-- #include file="dataconn.inc" --><!-- DataShape.asp -->2. <%3. Dim rsPublishers4. Dim rsTitles5. Dim strShapeConn6. Dim strShape
7. Set rsPublishers = Server.CreateObject("ADODB.Recordset")
8. strShapeConn = "Provider = MSDataShape; Data Provider = SQLOLEDB; Data Source= Hogwartz; " & _9. " Initial Catalog= pubs; User ID= sa; Password= letmein"
10. strShape = "SHAPE {SELECT * FROM Publishers } APPEND ({SELECT * FROM Titles} " & _11. " RELATE Pub_ID TO Pub_ID) AS rsTitles "
12. rsPublishers.Open strShape, strShapeConn
13. 'Loop through the publishers14. Response.Write "<UL>"15. While Not rsPublishers.EOF16. Response.Write "<LI>" & rsPublishers("Pub_Name")
17. 'Now the titles18. Response.Write "<UL>"19. Set RsTitles = rsPublishers("rsTitles").Value
20. 'Loop through the titles21. While Not rsTitles.EOF22. Response.Write "<LI>" & rsTitles("title")23. rsTitles.MoveNext24. Wend25. Response.Write "</UL>"
26. 'Move to the next publishers27. rsPublishers.MoveNext28. Wend29. Response.Write "</UL>"
30. rsPublishers.Close31. Set rsPublishers = Nothing32. Set rsTitles = Nothing33. %>
Bina Nusantara
Data Shaping