ASP Programming Example: 20 very useful examples in ASP programming

Source: Internet
Author: User
Tags connect variables table name first row unsupported valid how to use sql access
Programming

1. How to use ASP to determine the virtual physical path of your website

A: Use the MapPath method < p align="center" >< font size="4" face="Arial" >< b >
The Physical path to this virtual website is:
< /b >< /font >
< font color="#FF0000" size="6" face="Arial" >
< %= Server.MapPath("\"% >
< /font >< /p >
2. How do I know the browser used by the user?
Answer: Use the Request object method
strBrowser=Request.ServerVariables("HTTP_USER_AGENT"
If Instr(strBrowser,"MSIE" < > 0 Then
Response.redirect("ForMSIEOnly.htm"
Else
Response.redirect("ForAll.htm"
End If

3. How to calculate the average number of repeated visits per day

Answer: the solution

< % startdate=DateDiff("d",Now,"01/01/1990"
if strdate< 0 then startdate=startdate*-1
avgvpd=Int((usercnt)/startdate) % >

Show results

< % response.write(avgvpd) % >
that is it.this page have been viewed since November 10,1998

4. How to display random images

< % dim p,ppic,dpic
ppic=12
randomize
p=Int((ppic*rnd)+1)
dpic="graphix/randompics/"&p&".gif"
% >

Show

< img src="< %=dpic% >" >

5. How to get back to the previous page

For:< a href="< %=request.serverVariables("Http_REFERER"% >" >preivous page< /a >

Or with pictures such as:< img src="http://www.webjx.com/htmldata/2005-12-23/arrowback.gif" alt="< %=request.serverVariables("HTTP_REFERER"% >" >

6. How to determine the IP address of each other

For:< %=Request.serverVariables("REMOTE_ADDR)% >

7. How to link to a picture

For:< % @Languages=vbs cript % >
< % response.expires=0
strimagename="graphix/errors/erroriamge.gif"
response.redirect(strimagename)
% >

8. Forced Enter Password dialog box

A: Put this sentence on the beginning of the page

< % response.status="401 not Authorized"
response.end
% >

9. How to pass variables from one page to another

A: Use the HIDDEN type to pass variables

< % form method="post" action="mynextpage.asp" >
< % for each item in request.form % >
< input namee="< %=item% >" type="HIDDEN"
value="< %=server.HTMLEncode(Request.form(item)) % >" >
< % next % >
< /form >
10. Why I use MsgBox in the ASP program, the program error said no permissions

A: Because the ASP is the server running, if you can display a dialog box in the server, then you have to wait for someone to make sure that your program can continue to perform, and the general server will not be guarded, so Microsoft has to prohibit this function, and casually tell you (ha) do not have permission. However, ASP and client-side scripting can be combined to display a dialog box, as follows:

< % yourVar="测试对话框"% >
< % s cript language='javas cript' >
alert("< %=yourvar% >"
< /script>

11. There is no way to protect their source code, do not give people to see

A: You can download a Microsoft Windows S Cript encoder, which can encrypt the ASP scripts and client Javas cript/vbs cript scripts ... However, after the client is encrypted, only IE5 can execute, server-side script encryption, only the server installed with S Cript Engine 5 (installed a IE5 have) to perform.

12. How can I transfer query string from one ASP file to another?

A: The former document adds the following sentence: Response.Redirect ("Second.asp?" & Request.ServerVariables ("Query_string")

13.global.asa files always don't work?

A: Only the web directory is set to Web application, Global.asa is valid, and global.asa the root directory of a Web application is valid. IIS4 can use Internet Service Manager to set application setting how can I make an HTM file Execute script code just like an ASP file?

14. How can I make an HTM file Execute script code like an ASP file?

Answer: Internet sevices Manager-> select Default Web Site-> right mouse button-> Menu Properties-〉 home Directory-> Application settings (Application Setting)-> Click button "Configuration"-> App mapping-> Click button "ADD"-> Executable browse select \winnt\system32\inetsrv\asp. DLL EXTENSION input HTM method exclusions input put.delete all OK. However, it should be noted that the HTM is also handled by Asp.dll, and the efficiency will be reduced.

15. How to register Components

Answer: There are two ways.

The first method: Manually registering DLLs This method is used from IIS 3.0 to IIS 4.0 and other Web servers. It requires you to run down the command line, into the directory containing the DLL, and enter: regsvr32 component_name.dll for example C:\temp\regsvr32 AspEmail.dll It registers specific information about the DLL into the registry in the server. This component can then be used on the server, but there is a flaw in this approach. When the component is registered with this method, the component must be set to the appropriate NT anonymous account to execute the DLL. In particular, some components need to read the registry, so the method of registering the component is simply using the server without MTS, to unregister the DLL, using: regsvr32/u Aspobject.dll Example c:\temp\regsvr32/u Aneiodbc.dll

The second approach: using MTS (Microsoft Transaction Server) MTS is a new feature of IIS 4, but it provides a great deal of improvement. MTS allows you to specify that only privileged users have access to the component, greatly improving the security settings on the Web server. The steps for registering a component on MTS are as follows:

1 Open the IIS Management Console.

2) Expand Transaction Server, right-click "pkgs Installed" and select "New Package".

3) Click "Create an empty package".

4) name the package.

5 Specify the Administrator account or use "interactive" (if the server is often logged in with the administrator).

6 now use the right mouse button to click the "Components" that you started underneath the package you just created. Select "New then Component".

7 Select "Install New Component".

8 Locate your. dll file and select next to complete.

To delete this object, simply select its icon, and then select Delete.

Note: In particular, note the second method, which is the best way to debug your own writing components, without having to reboot the machine every time.

ASP to connect to an Access database:

<%@ language=VBs cript%>
<%
dim conn,mdbfile
mdbfile=server.mappath("数据库名称.mdb"
set conn=server.createobject("adodb.connection"
conn.open "driver={microsoft access driver (*.mdb)};uid=admin;pwd=数据库密码;dbq="&mdbfile
%>

ASP to connect with SQL database:

<%@ language=VBs cript%>
<%
dim conn
set conn=server.createobject("ADODB.connection"
con.open "PROVIDER=SQLOLEDB;DATA SOURCE=SQL服务器名称或IP地址;UID=sa;PWD=数据库密码;DATABASE=数据库名称
%>

To set up a Recordset object:

set rs=server.createobject("adodb.recordset"
rs.open SQL语句,conn,3,2

How to use SQL frequently used commands:

(1) Data record filtering:

sql="select * from 数据表 where 字段名=字段值 order by 字段名 [desc]"
sql="select * from 数据表 where 字段名 like '%字段值%' order by 字段名 [desc]"
sql="select top 10 * from 数据表 where 字段名 order by 字段名 [desc]"
sql="select * from 数据表 where 字段名 in ('值1','值2','值3')"
sql="select * from 数据表 where 字段名 between 值1 and 值2"

(2) Update data records:

sql="update 数据表 set 字段名=字段值 where 条件表达式"
sql="update 数据表 set 字段1=值1,字段2=值2 …… 字段n=值n where 条件表达式"

(3) Delete data records:

sql="delete from 数据表 where 条件表达式"
sql="delete from 数据表" (将数据表所有记录删除)

(4) Adding data records:

sql="insert into 数据表 (字段1,字段2,字段3 …) valuess (值1,值2,值3 …)"
sql="insert into 目标数据表 select * from 源数据表" (把源数据表的记录添加到目标数据表)

(5) Data record statistic function:

AVG (field name) to derive a table column average

Count (*| field name) statistics on the number of data rows or the number of data rows that have a value for a column

Max (field name) gets the maximum value of a table column

Min (field name) gets the smallest value of a table column

sum (field name) adds the value of the data bar

How to reference the above function:

sql="select sum(字段名) as 别名 from 数据表 where 条件表达式"
set rs=conn.excute(sql)

Using RS ("Alias" to obtain the value of the unified, other functions using the same.

(5) The establishment and deletion of the data table:

CREATE TABLE 数据表名称(字段1 类型1(长度),字段2 类型2(长度) …… )
例:CREATE TABLE tab01(name varchar(50),datetime default now())
DROP TABLE 数据表名称 (永久性删除一个数据表)

19. Method of Recordset object:

Rs.movenext moves the record pointer down one row from the current position

Rs.moveprevious move the record pointer up one row from the current position

Rs.movefirst move the record pointer to the first row of the datasheet

Rs.movelast move the record pointer to the last row of the datasheet

Rs.absoluteposition=n move the record pointer to the nth row of the datasheet

Rs.absolutepage=n move the record pointer to the first row of page N

Rs.pagesize=n set every page to N records

Rs.pagecount returns the total number of pages based on pagesize settings

Rs.recordcount returns the total number of records

RS.BOF returns whether the record pointer is over the first end of the datasheet, True indicates Yes, FALSE is no

Rs.eof returns whether the record pointer is over the end of the datasheet, True indicates Yes, FALSE is no

Rs.delete deletes the current record, but the record pointer does not move down

Rs.addnew add records to the end of the datasheet

Rs.update Update datasheet Record

---------------------------------------

Recordset Object Method

Open method

Recordset. Open source,activeconnection,cursortype,locktype,options

Source

The Recordset object can connect to the command object through the Source property. The source parameter can be a command object name, a section of SQL command, a specified data table name, or a stored Procedure. If this argument is omitted, the system takes the source property of the Recordset object.

ActiveConnection

The Recordset object can connect connection objects by ActiveConnection properties. The ActiveConnection can be a connection object or a string parameter containing the database connection information (ConnectionString).

CursorType

The CursorType parameter of the Recordset object Open method indicates what cursor type will start the data, including adOpenForwardOnly, adOpenKeyset, adOpenDynamic, and adOpenStatic. It is described as follows:

--------------------------------------------------------------

Constants Constant Numerical description

-------------------------------------------------------------

adOpenForwardOnly 0 defaults to start a cursor that can only be moved forward (Forward only).

adOpenKeyset 1 launches a keyset type of cursor.

adOpenDynamic 2 launches a dynamic-type cursor.

adOpenStatic 3 launches a static type of cursor.

-------------------------------------------------------------

These cursor types will directly affect all properties and methods of the Recordset object, and the following list illustrates the differences between them.

-------------------------------------------------------------

Recordset Properties adOpenForwardOnly adOpenKeyset adopendynamic adOpenStatic

-------------------------------------------------------------

AbsolutePage does not support read-write writable

AbsolutePosition does not support read-write writable

ActiveConnection can read, write, read, write, read and write

BOF read-only read-only read-only

Bookmark does not support read-write writable

CacheSize can read, write, read, write, read and write

CursorLocation can read, write, read, write, read and write

CursorType can read, write, read, write, read and write

EditMode read-only read-only read-only

EOF read-only read-only read-only

Filter can read, write, read, write, read and write

LockType can read, write, read, write, read and write

MarshalOptions can read, write, read, write, read and write

MaxRecords can read, write, read, write, read and write

PageCount does not support read-only read-only

PageSize can read, write, read, write, read and write

RecordCount does not support read-only read-only

Source can read, write, read, write, read and write

State read-only read-only read-only

Status read-only read-only read-only

AddNew Support Support

CancelBatch Support Support

CancelUpdate Support Support

Clone does not support unsupported

Close support support for support

Delete Support support for support

GetRows Support Support

Move does not support support support

MoveFirst Support Support

MoveLast support Support support is not supported

MoveNext Support Support

MovePrevious support Support support is not supported

NextRecordset Support Support

Open Support support supporting support

Requery Support Support Support support

Unsupported support support is not supported by Resync

Supports Support Support

Update Support support supporting support

UpdateBatch Support Support

--------------------------------------------------------------

Where the NextRecordset method does not apply to Microsoft Access databases.

LockType

The LockType parameter of the Recordset object's Open method represents the lock type to take, and if this argument is omitted, then the system takes the LockType property of the Recordset object as the preset value. The LockType parameters include adLockReadOnly, adlockprssimistic, adLockOptimistic, and adLockBatchOptimistic, as described below:

-------------------------------------------------------------

Constants Constant Numerical description

--------------------------------------------------------------

adLockReadOnly 1 defaults, the Recordset object starts as read-only and cannot run AddNew, Update, and Delete methods

Adlockprssimistic 2 When the data source is being updated, the system temporarily locks the actions of other users to maintain data consistency.

adLockOptimistic 3 When the data source is being updated, the system does not lock other users ' actions, other users can add, delete, and change the operation of the data.

adLockBatchOptimistic 4 When the data source is being updated, other users must change the CursorLocation property to Adudeclientbatch to add, delete, and modify the data.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.