home *** CD-ROM | disk | FTP | other *** search
/ H4CK3R 4 / hacker04 / 04_HACK04.ISO / src / ASP / database_add.asp < prev    next >
Encoding:
Text File  |  2001-06-08  |  8.3 KB  |  234 lines

  1. <%
  2. '*******************************************************
  3. '*     ASP 101 Sample Code - http://www.asp101.com     *
  4. '*                                                     *
  5. '*   This code is made available as a service to our   *
  6. '*      visitors and is provided strictly for the      *
  7. '*               purpose of illustration.              *
  8. '*                                                     *
  9. '* Please direct all inquiries to webmaster@asp101.com *
  10. '*******************************************************
  11. %>
  12.  
  13. <%' Defining some constants to make my life easier!
  14. ' Begin Constant Definition
  15.     
  16.     ' DB Configuration constants
  17.     ' Fake const so we can use the MapPath to make it relative.
  18.     ' After this, strictly used as if it were a Const.
  19.     Dim DB_CONNECTIONSTRING
  20.     
  21.     ' ODBC
  22.     'DB_CONNECTIONSTRING = "DRIVER={Microsoft Access Driver (*.mdb)};" _
  23.     '    & "DBQ=" & Server.Mappath("./db_scratch.mdb") & ";"
  24.  
  25.     ' OLE DB
  26.     DB_CONNECTIONSTRING = "Provider=Microsoft.Jet.OLEDB.4.0;" _
  27.         & "Data Source=" & Server.Mappath("db_dsn.mdb") & ";"
  28.  
  29.     ' We don't use these, but we could if we neeeded to.
  30.     'Const DB_USERNAME = "username"
  31.     'Const DB_PASSWORD = "password"
  32.     
  33.     'Now we override the above settings to use our SQL server.
  34.     'Delete the following line to use the sample Access DB.
  35.     DB_CONNECTIONSTRING = Application("SQLConnString")
  36.  
  37.     ' ADODB Constants
  38.     ' You can find these in the adovbs.inc file
  39.     ' Do a search for it and it should turn up somewhere on the server
  40.     ' If you can't find it you can download our copy from here:
  41.     '     http://www.asp101.com/samples/download/adovbs.inc
  42.     ' It may not be the most recent copy so use it at your own risk.
  43. %>
  44.     <!-- #INCLUDE FILE="adovbs.inc" -->
  45. <%
  46. ' End Constant Definition
  47. %>
  48.  
  49. <%
  50. Dim I            ' Standard looping var
  51. Dim strSQL       ' String variable for building our query
  52. Dim iRecordAdded ' Id of added record
  53.  
  54. 'We're going to keep this as simple as we can.
  55. '  1. Create a Recordset object
  56. '  2. Connect the Recordset to the table
  57. '  3. Add a new record to the Recordset
  58. '  4. Set the values of the Recordset
  59. '  5. Update the table
  60. '  6. Close the Recordset
  61.  
  62. 'Step 1:
  63.     Dim objRecordset
  64.     Set objRecordset = Server.CreateObject("ADODB.Recordset")
  65.  
  66.     ' The following syntax is also acceptable if you move it outside of the
  67.     ' script delimiters.  I prefer to Dim and then set it like any other
  68.     ' variable, but it really doesn't make too big a difference.
  69.  
  70.     '<OBJECT RUNAT=server PROGID=ADODB.Recordset ID=objRecordset></OBJECT>
  71.  
  72. 'Step 2:
  73.     ' The syntax for the open command is
  74.     ' recordset.Open Source, ActiveConnection, CursorType, LockType, Options 
  75.     '
  76.     ' Source
  77.     '   In this case it's our SQL statement.  It could also be a
  78.     '   Table Name, a command object, or a stored procedure.
  79.     ' ActiveConnection
  80.     '   We use a string which contains connection information.  It could also
  81.     '   be a connection object which is faster if you need to open multiple
  82.     '   recordsets. 
  83.     ' CursorType
  84.     '   Doesn't matter too much in this case since I'm not going to be doing
  85.     '   much with the records.  I'm opening it as a static so I can get a
  86.     '   recordcount.
  87.     ' LockType
  88.     '   Specifies how the provider should lock the data.  We'll use pessimistic
  89.     '   so that it'll lock as soon as we start editing and basically ensure a
  90.     '   successful update.
  91.     ' Options
  92.     '   Tells what type of source we're using if it's not a command object
  93.     '
  94.     ' Most of the above are optional to some degree.  It's usually better
  95.     ' to set them so you know what their settings are.  It'll avoid the
  96.     ' defaults coming back to haunt you when you try and do something they
  97.     ' don't allow.
  98.  
  99.     ' I'm prebuilding our SQL query so it's easier to print
  100.     ' out in case we need to debug later.  I'm using a query
  101.     ' that will return no results since I'm really just trying
  102.     ' to add a new one and am not interested in the current
  103.     ' data in the table.
  104.     strSQL = "SELECT * FROM scratch WHERE 0=1;"
  105.  
  106.     ' This is the way I normally would open this RS:
  107.     objRecordset.Open strSQL, DB_CONNECTIONSTRING, adOpenKeyset, adLockPessimistic, adCmdText
  108.     
  109.     ' You could also do it step by step if you want:
  110.     'objRecordset.Source           = "table_name"
  111.     'objRecordset.ActiveConnection = DB_CONNECTIONSTRING
  112.     'objRecordset.CursorType       = adOpenKeyset
  113.     'objRecordset.LockType         = adLockPessimistic
  114.     'objRecordset.Open
  115.  
  116. 'Step 3:        
  117.     ' To add a new record to the current recordset we naturally call the
  118.     ' AddNew Method.
  119.     objRecordset.AddNew
  120.  
  121.     ' If you're not sure if your RS supports Adding a New record you can check
  122.     ' via the following command.  This will return True if it does, False
  123.     ' otherwise:
  124.     ' objRecordset.Supports(adAddNew)
  125.  
  126.     ' Another Note: It takes arrays as input and gets confusing so I usually
  127.     ' don't do it, but you can actually specify the values on the AddNew line
  128.     ' (combining steps 3 and 4) like this:
  129.     ' objRecordset.AddNew Array("text_field", "integer_field", "date_time_field"), Array("Some Text", CInt(Day(Date())), Now())
  130.  
  131. 'Step 4:
  132.     ' Here we set the values of each field.  You'll notice we don't set the
  133.     ' id field.  Since it's the primary key, I've set it as an autonumber in
  134.     ' the DB so it'll take care of creating the value for us.
  135.     
  136.     ' I'm just pulling any values I want for insertion here. You'd probably use
  137.     ' something from a form or other user input.  Just make sure you're putting
  138.     ' the right types of data into the fields.
  139.     
  140.     ' String / Text Data Type
  141.     objRecordset.Fields("text_field") = CStr(WeekdayName(WeekDay(Date())))
  142.     
  143.     ' Integer Data Type
  144.     objRecordset.Fields("integer_field") = CInt(Day(Now()))
  145.     
  146.     ' Date / Time Data Type
  147.     objRecordset.Fields("date_time_field") = Now()
  148.  
  149. 'Step 5:
  150.     ' Couldn't be too much easier:
  151.     objRecordset.Update
  152.  
  153. 'Show the user something:
  154.     ' Get the DB assigned ID of the record we just added.
  155.     iRecordAdded = objRecordset.Fields("id").Value
  156.     
  157.     ' Tell people which record we added.
  158.     Response.Write "Record id " & iRecordAdded & " added!"
  159.  
  160. 'Step 6:
  161.     ' Finally we close the recordset and release the memory used by the
  162.     ' object variable by setting it to Nothing (a VBScript keyword)
  163.     objRecordset.Close
  164.     Set objRecordset = Nothing
  165.  
  166.  
  167. '********************************
  168. ' This is the end of the sample!
  169. '********************************
  170.  
  171. 'Show Table
  172.     ' Feel free to skip this area. (Ignore the man behind the curtain!)
  173.     ' I'm just showing the Table so you have something to look at when
  174.     ' you view the sample.
  175.     Dim objCleanUpRS
  176.     Dim iRecordCount
  177.  
  178.     strSQL = "SELECT * FROM scratch ORDER BY id;"
  179.  
  180.     Set objCleanUpRS = Server.CreateObject("ADODB.Recordset")
  181.     objCleanUpRS.Open strSQL, DB_CONNECTIONSTRING, adOpenStatic, adLockReadOnly, adCmdText
  182.  
  183.     Response.Write "<TABLE BORDER=""1"" CELLSPACING=""2"" CELLPADDING=""2"">" & vbCrLf
  184.     Response.Write vbTab & "<TR>" & vbCrLf
  185.     Response.Write vbTab & vbTab & "<TD><B>id</B></TD>" & vbCrLf
  186.     Response.Write vbTab & vbTab & "<TD><B>text_field</B></TD>" & vbCrLf
  187.     Response.Write vbTab & vbTab & "<TD><B>integer_field</B></TD>" & vbCrLf
  188.     Response.Write vbTab & vbTab & "<TD><B>date_time_field</B></TD>" & vbCrLf
  189.     Response.Write vbTab & "</TR>" & vbCrLf
  190.  
  191.     If Not objCleanUpRS.EOF Then
  192.         objCleanUpRS.MoveFirst
  193.         'Show data
  194.         Do While Not objCleanUpRS.EOF
  195.             Response.Write vbTab & "<TR>" & vbCrLf
  196.             For I = 0 To objCleanUpRS.Fields.Count - 1
  197.                 Response.Write vbTab & vbTab & "<TD>" & objCleanUpRS.Fields(I) & "</TD>" & vbCrLf
  198.             Next
  199.             Response.Write vbTab & "</TR>" & vbCrLf
  200.             objCleanUpRS.MoveNext
  201.         Loop
  202.     End If
  203.     Response.Write "</TABLE>" & vbCrLf
  204.  
  205.     ' Get recordcount so we know if we need to clean up.
  206.     iRecordCount = objCleanUpRS.RecordCount
  207.  
  208.     objCleanUpRS.Close
  209.     Set objCleanUpRS = Nothing
  210.  
  211. ' Now this is REALLY behind the curtain!
  212.  
  213. ' Normally I'd cut you off right here and do the rest behind the scenes;
  214. ' however, since this has to do with the DB you were just writing to,
  215. ' I'll give you a treat and let you see some of our administative /
  216. ' housekeeping code!
  217.  
  218. ' Now we clean up!
  219. ' Basically, to keep things manageable, I'm checking the DB
  220. ' to keep it under a dozen or so records.
  221.     If iRecordCount >= 12 Then
  222.         Set objCleanUpRS = Server.CreateObject("ADODB.Recordset")
  223.         objCleanUpRS.Open strSQL, DB_CONNECTIONSTRING, adOpenDynamic, adLockPessimistic, adCmdText
  224.  
  225.         For I = 1 to 10
  226.             objCleanUpRS.MoveFirst
  227.             objCleanUpRS.Delete
  228.         Next
  229.  
  230.         objCleanUpRS.Close
  231.         Set objCleanUpRS = Nothing
  232.     End If
  233. %>
  234.