First, preface mentioned the ASP operation database, most people will think of: shared connection string constr, conn.execute sqlcmd mode execution command, recordset.open sql, conn, 1, 1 acquisition record Set, this method is indeed adopted by 99% of people or companies. For the error generated during the operation database, I am afraid that 99% will not process it. Either join the ON Error Resume next "easy" to jump over the beginning of the program, or let the error message together with the error code "Ruth" in front of the viewer . For the former case, it may generate a wonderful weird outcomes, the latter case, may expose your sensitive information at a certain time (such as connecting the database), affecting the security of the website. Of course, there is still an individual responsible programmer comrades to add if Err.xxxx that is easy to generate errors to handle possible errors, but this doesn't seem to have a good way, and you may miss it. I didn't want to understand why IN Error Goto existing in VB and ASP.NET, is delayed in the ASP. Also, when you use on Error Resume next, you don't want to get next, sorry, no way, you can only "implement it". Look at the exception mechanisms of other languages, try..catch..finally is really cool!
Sarrely, don't introduce new content such as an abnormal mechanism, after all, the ASP language itself decides that this is impossible (ASP.NET is implemented), just wants the most common most popular in the ASP. In the wrong database operation, find a valid error handling method, and encapsulate conn, recordset, etc. to achieve the maximum streamline. Then there is the following database class.
Second, the database class 1, the function is just as mentioned earlier, the purpose of this class is to encapsulate the cumbersome operations such as AdoDb.Connection, AdoDb.Recordset and implement errors in the class. Now look at the members, attributes and methods of the class: 1) Members: (no public or protective members) 2) Properties: classname- Return to class Version- Return version LastError- Return the last error IgnoreError-Setup / return whether to ignore database errors Connection- Returns the connection object (AdoDb.Connection) Connectionstring- Settings / Return Connection Strings (This example is SQL Server, such as other please set up according to actual settings) FIELDCOUNT, PageSize, PageCount, AbsolutePage, AbsolutePosition, Bof, EOF- Please refer AdoDb.recordset Corresponding Content 3) Method: Setup- Set the account, password, database name, host / ip connect-Connection database close-turn the database connection and release the database query command and return to the Data Set EXESQL- Execute SQL Command (Do not return database) FieldName- Field Name Fields - Return the value of the specified (serial number or field name) field Data - equipped with MoveNext, MovePrevious, MoveFirst, MoveLast- Please refer to AdoDb.Recordset
2, realize the code (dbsql.inc.asp) content is too long, click here to open / fold ... <% '======================== ========================================================= 'Class Name: CLSDB 'Design By: Peng Guohui' Date: 2003-12-18 'site: http://kacarton.yeah.net/' email: kacarton@sohu.com 'modify:' 2004-6-25: After upgrade The data engine, the error code is less than 0 (or the ASP logs "'defined variation), modify error detection err.Number> 0 ==> Err.Number <> 0' 2004-6-30: Modify Error handling, Ignore the non-error nature of the cursor type change "========================================================================================================== ========================================= Class CLSDB
'Name of this class' var string '@access private' @see property: name private m_strname
'Version of this class' var string '@access private' @see property: Version Private M_STRVERSION
'Error Object' @var adodb.connection.errors '@access private' @see property: LastError Private M_lasterror
'Ingore all connection.errors' var boolean '@Access private' @see property: ignorerror private m_ignorerror
'Connection Object' Var AdoDb.Connection '@Access Private' @see Property: Connection Private M_Connection 'Is Connection to Database?' Var Boolean '@Private Private M_bisconnect
'Recordset' Var Recordset '@access Private Private M_Recordset
'Connection String' Var String '@access Private' @see Property: Connectionstring Private M_Connestr
'Database Server Host Name OR IP' Var String '@access Private' @see Property: Host Private M_Strhost
'Database Name' Var String '@access Private' @see Property: Database Private M_STRDATABASE
'Account to Connection Database' Var String '@access Private' @see Property: UserName Private M_Username
'Password to connection database' Var string '@access private' @see protety: password private m_password
'get class name attribute.' usage: Otemplate.Name 'Access Public Public Property Get ClassName () ClassName = m_StrName End Property
'get class version attribute.' usage: Otemplate.Version 'Access Public Public Property Get Version () Version = M_STRVERSION End Property
'Get class last error messages.' Usage: Otemplate.lasterror '@access public public Property get last laterror () lasterror = m_lasterror End Property
'Get or set ignore connection.errors public property get ignorerror () ignorerror = m_ignorerror end printy
Public property let ignoreerror (Byval value) m_ignorerror = value End Property
'Get connection public protection = m_connection endproperty
'Get connection string Public Property Get ConnectionString () ConnectionString = m_ConneStr End Property' Set connection string Public Property Let ConnectionString (ByVal Value) m_ConneStr = Value End Property
'Get Data Fields Count Public Property Get Fieldcount () Fieldcount = m_RecordSet.fields.count End Property
'Get Recordset PageSize () on error resume next pagesize = m_recordset.pagesize = m_recordset.pagesize if err.Number <> 0 Then ShrowError ("CAN NOT PAGESIZE!") End Property
'Set recordset page size public property letted (byval value) on error resume next m_recordset.pageSize = value if err.Number <> 0 Then ShrowError ("Can NOT PageSize to" & value) End Property
'Get Recordset Page Count () PageCount = m_record.com.pageCount End Property
'Get Recordset Record Count Public Property Get Record () ON Error ResMe Next Recount = m_recordset.recordcount = m_recordset.recordcount IF Err.Number <> 0 Then ShrowError ("Get Recordcount Error.") End Property
'Get RecordSet Absolute Page Public Property Get AbsolutePage () on error resume next AbsolutePage = m_RecordSet.AbsolutePage if err.number <> 0 then ShowError ( "Can not get AbsolutePage!") End Property
'Set RecordSet Absolute Page Public Property Let AbsolutePage (ByVal Value) on error resume next m_RecordSet.AbsolutePage = Value if err.number <> 0 then ShowError ( "Can not set AbsolutePage to" & Value) End Property
'Get RecordSet Absolute Position Public Property Get AbsolutePosition () on error resume next AbsolutePosition = m_RecordSet.AbsolutePosition if err.number <> 0 then ShowError ( "Can not get AbsolutePosition!") End Property' Set RecordSet Absolute Position Public Property Let AbsolutePosition ( BYVAL VALUE) ON Error ResMe NEXT M_RECORDSET.ABSOLUTEPSITION = VALUE IF Err.Number <> 0 THEN Showerror ("Can NOT SET ABSOLUTEPSITION TO" & Value) End Property
'Bof public property get bof () bof = m_recordset.bof end protection
'EOF PUBLIC Property Get EOF () EOF = m_Recordset.eof End Property
'Setup the databease host name, database name, User name (account), password Public Sub Setup (Account, Password, Database, Host) m_UserName = Account m_Password = Password if Database <> "" then m_strDatabase = Database if Host <> " "THEN M_STRHOST = HOST M_CONNESTR =" Driver = {SQL Server}; Server = "& M_StrHost &"; Database = "& _ M_STRDATABASE &"; UID = "& M_Username &"; PWD = "& M_Password &" End Sub
'Connect to database Public Function Connect () on error resume next m_Connection.Open m_ConneStr if err.number <> 0 Then ShowError ( "Connection Error Database: (Server:" & m_strHost & ", Database:" & m_strDatabase & ")" ) m_bisconnect = true connect = true 'Todo: // end function
'Diconnect database Public Function Close () on error resume next Set m_RecordSet = Nothing Set m_Connection = Nothing m_bIsConnect = false Close = true if err.number <> 0 then ShowError ( "Error Database Connectivity off") end Function' Query Public Sub Query (SQLCommand) on error resume Next if not m_bIsConnect then Connect Set m_RecordSet = Server.CreateObject ( "Adodb.Recordset") 'Set m_RecordSet = m_Connection.Execute (SQLCommand) m_RecordSet.Open SQLCommand, m_Connection, 1, 1 if err.number <> 0 Then Showerror (SqlCommand): EXIT SUB IF M_CONNECTION.ERRORS.COUNT> 0 and m_ignorerror = false the processError (SqlCommand) end sub
'ExeSQL Command Public Sub ExeSQL (SQLCommand) on error resume Next if not m_bIsConnect Connect m_Connection.Execute SQLCommand if err.number <> 0 then ShowError (SQLCommand) then: exit sub if m_Connection.Errors.Count> 0 And m_IgnoreError = false then Processerror (SQLCommand) end sub
'Get Fields Name Public Function FieldName (Byval Fieldid) On Error Resume Next FieldName = M_RecordSet.fields (Fieldid) .name if Err.Number <> 0 THEN ShowError ("You cannot read the field" & FieldID & "Name!") END Function
'GET Fields Data Public Function Fields (Byval Fieldid) on Error Resume Next Fields = m_recordset.fields (Fieldid) if Err.Number <> 0 THEN ShowError ("You cannot read field" & FieldID & "Data!") End Function
'Get Fields Data Public Function Data (Byval Fieldid) On Error Resume Next Data = m_RecordSet.fields (Fieldid) if Err.Number <> 0 THEN ShowError ("You cannot read" & FieldID & "Data!")' IF M_Connection. Errors.count> 0 Then Showerror ("You cannot read" & FieldID & "Data!") End Function 'Move To Next Record Public Sub Movenext () on Error ResMe next if m_bisconnect the m_recordset.movenext if Err.Number <> 0 Then ShrowError ("Movenext Error") End Sub
'Move to Previous Record Public Sub MovePrevious () on Error ResMe next if m_bisconnect kil_recordset.moveprevious if err.Number <> 0 Then ShrowError ("MovePrevious Error" End Sub
'Move to First Record Public Sub Movefirst () on Error ResMe Next If M_Bisconnect The M_RecordSet.movefirst IF Err.Number <> 0 Then ShrowError ("MoveFirst Error" End Sub
'Move to Last Record Public Sub MoveLast () ON Error ResMe Next IF M_Bisconnect The M_RecordSet.movelast IF Err.Number <> 0 Then Showerror ("MoveLast Error" End Sub
'2004-6-30 private sub processerror (byval sqltxt) for i = 0 to m_connection.erroNert-1 if m_connection.errors.Item (i) .Number <> 0 Then ShowError (SQLTXT) Next End Sub
'This function is called whenever an error occurs and will handle the error' Additionally the error message will be saved in m_strLastError. '@Param $ msg a string containing an error message' @access private '@return void Private Sub ShowError (ByVal sqltxt ) for i = 0 to m_connection.errors.count-1 Response.write m_connection.erroS.Item (i) & "(" & m_connection.erroS.Item (i) .Number & ")
" Next m_lasterror = err .Descriptionm_connection.errors.clear response.write
------------------------------------- -----------------
"& _" "& Sqltxt &" font> "'response.write"
-------------------------------------------------- ----
"& _ '" "& left (SQLTXT, 10) &" ... (Error message has been blocked), please contact the website administrator! Font> "Response.end End Sub
'Class constructor, set class default attributes, you can change it Private Sub class_Initialize m_strName = "clsDB" m_strVersion = "1.0" Set m_Connection = Server.CreateObject ( "ADODB.Connection")' here to modify your default database connection Value Setup "SA", "Password", "Northwind", "(local)" m_bisconnect = false m_ignorerror = false End Sub
'Class Destructor, Free Memory. Private Sub Class_Terminate Set M_Recordset = Nothing Set M_Connection = Nothing End Sub
END CLASS
%>
3, use example <% function htmlencode (str) if isnull (str) Then htmlencode = "_ else htmlencode = server.htmlencode STR) End FunctionDim SQL, ISET SQL = New CLSDB SQL.Connect Sql.exesql ("Update Customers Set Address = 'The' WHERE ID = 1" of the People's Republic of China) SQL.Query ("Select * from customers") Response.write