杰 的个人资料杰 杰 Base照片日志列表 工具 帮助

日志


4月22日

MS SQL Server 列数据表字段脚本

SELECT SysObjects.Name as TableName,
  SysColumns.Name as ColumnsName,
        SysTypes.Name as DateType,
        SysColumns.Length as DateLength
FROM SysObjects,SysTypes,SysColumns
WHERE (Sysobjects.Xtype = 'u')
AND Sysobjects.Id = Syscolumns.Id
AND SysTypes.XType = Syscolumns.XType
AND SysTypes.Name <> 'sysname'
AND SysObjects.name = '用户表名'
2月19日

ASP.NET 记录页面错误及自定义错误页

defualt.aspx.cs 上加记录错误log到系统事件日志onerr方法 可将代码写到通用继承页面中

protected override void OnError(EventArgs e)
{
// At this point we have information about the error
HttpContext ctx = HttpContext.Current;
Exception exception = ctx.Server.GetLastError();
string errorInfo = "错误URL: " + ctx.Request.Url.ToString() + "\n源: " + exception.Source + "\n消息Message: " + exception.Message + "\n堆栈: " + exception.StackTrace;
//ctx.Response.Write(errorInfo);
// --------------------------------------------------
// To let the page finish running we clear the error
// --------------------------------------------------
//ctx.Server.ClearError();
string LogName = "MyWebError";
if (!System.Diagnostics.EventLog.SourceExists(LogName))
{
System.Diagnostics.EventLog.CreateEventSource(LogName, "App");
}
System.Diagnostics.EventLog el = new System.Diagnostics.EventLog();
el.Source = LogName;
el.WriteEntry(errorInfo, System.Diagnostics.EventLogEntryType.Error);
base.OnError(e);
}
web.config 上修改友好错误页
<customErrors mode="On" defaultRedirect="MyErrorPage.htm">
</customErrors>

ASP.NET WEB用户控件下拉框

WebUserControl1.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="WebApplication1.WebUserControl1" %>   

<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>   

<asp:DropDownList ID="DropDownList1" runat="server" >
</asp:DropDownList>

WebUserControl1.ascx.cs

    

using System;
        using System.Data;
        using System.Configuration;
        using System.Collections;
        using System.Web;
        using System.Web.Security;
        using System.Web.UI;
        using System.Web.UI.WebControls;
        using System.Web.UI.WebControls.WebParts;
        using System.Web.UI.HtmlControls;
        using System.Data.SqlClient;    

namespace WebApplication1
        {
        public partial class WebUserControl1 : System.Web.UI.UserControl
        {
        private string pStrSql;
        private int pSelectedIdx;
        private string pLabelText;
        private bool pIsSelAll;
        protected void Page_Load(object sender, EventArgs e)
        {
        if (!Page.IsPostBack)
        {
        MakDropDownList();
        Label1.Text = this.pLabelText;
        }
        }
        public WebUserControl1()
        {
        pStrSql = "";
        pSelectedIdx = -1;
        }
        /// <summary>
        /// 控件属性SQL语句
        /// </summary>
        public string StrSql
        {
        set { pStrSql = value; }
        }
        /// <summary>
        /// 控件属性选中项的id
        /// </summary>
        public int SelectedIdx
        {
        set { pSelectedIdx = value; }
        }    

/// <summary>
        /// 下拉框标题
        /// </summary>
        public string LabelText
        {
        set { pLabelText = value; }
        }    

/// <summary>
        /// 是否要全选项
        /// </summary>
        public bool IsSetAll
        {
        set { pIsSelAll = value; }
        }
        protected void MakDropDownList()
        {
        if (this.pStrSql == string.Empty || this.pStrSql == null)
        {
        DropDownList1.Items.Clear();
        DropDownList1.Items.Add("没有数据");
        DropDownList1.Items[0].Value = "-1";
        }
        else
        {
        DropDownList1.Items.Clear();
        if (pIsSelAll)
        {
        DropDownList1.Items.Add("所有值");
        DropDownList1.Items[0].Value = "-1";
        }
        SqlConnection conn = new SqlConnection();
        conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnMain1"].ConnectionString;
        string sqlstr = this.pStrSql; //"SELECT ProductName,ProductID  FROM Products ORDER BY ProductID";
        SqlDataAdapter da = new SqlDataAdapter(sqlstr, conn);
        DataTable dt = new DataTable();
        da.Fill(dt);
        for (int i = 0; i < dt.Rows.Count; i++)
        {
        DropDownList1.Items.Add(dt.Rows[i][1].ToString());
        if (pIsSelAll)
        {
        DropDownList1.Items[i+1].Value = dt.Rows[i][0].ToString();
        }
        else
        {
        DropDownList1.Items[i].Value = dt.Rows[i][0].ToString();
        }
        }
        }
        }    

}
        }    

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<%@ Register Src="WebUserControl1.ascx" TagName="WebUserControl1" TagPrefix="uc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
        <head runat="server">
    <title>无标题页</title>
& amp; nbsp;   </head>
    <body>
    <form. id="form1" runat="server">
    <div>
    <uc1:WebUserControl1 id="WebUserControl1_1" StrSql="SELECT CategoryID, CategoryName FROM Categories" LabelText="产品分类"  runat="server">
    </uc1:WebUserControl1>
    <uc1:WebUserControl1 ID="WebUserControl1_2" runat="server" />
    &nbsp;
    <asp:Button ID="Button1" runat="server" nClick="Button1_Click" Text="Button" /><br />
        选择结果:<asp:Label ID="Label1" runat="server" ForeColor="#0000C0">ddddd</asp:Label></div>
    </form>
    </body>
    </html>
    

Default.aspx.cs

        using System;
        using System.Data;
        using System.Configuration;
        using System.Collections;
        using System.Web;
        using System.Web.Security;
        using System.Web.UI;
        using System.Web.UI.WebControls;
        using System.Web.UI.WebControls.WebParts;
        using System.Web.UI.HtmlControls;    

namespace WebApplication1
        {
        public partial class _Default : System.Web.UI.Page
        {
        protected void Page_Load(object sender, EventArgs e)
        {
        }    

protected void Button1_Click(object sender, EventArgs e)
        {
        Label1.Text = ((DropDownList)WebUserControl1_1.FindControl("DropDownList1")).SelectedItem.Value.ToString();
        }
        }
        }
    

Web.config

<connectionStrings>
<add name="ConnMain1" connectionString="Data Source=127.0.0.1;Initial Catalog=Northwind;User ID=sa" providerName="System.Data.SqlClient"/>
</connectionStrings>

9月19日

SqlServer分页存储过程

使用Northwind库Customer表
不带参数的分页
 
CREATE  PROCEDURE up_pagecutSample2
    @PageIndex INT, /*@PageIndex从计数,0为第一页*/
    @PageSize  INT, /*页面大小*/
    @RecordCount INT OUT, /*总记录数*/
    @PageCount INT OUT /*页数*/
AS
/*获取记录数*/
SELECT @RecordCount = COUNT(0) FROM dbo.customers
/*计算页面数据*/
SET @PageCount = CEILING(@RecordCount * 1.0 / @PageSize)
/*TOP记录数*/
DECLARE @TOPCOUNT INT
SET @TOPCOUNT = @RecordCount - @PageSize * @PageIndex
DECLARE @SQLSTR NVARCHAR(1000)
IF @PageIndex = 0 OR @PageCount <= 1
BEGIN
    SET @SQLSTR =N'SELECT TOP '+STR(@PageSize)+
    ' * FROM dbo.customers ORDER BY CustomerID DESC'
END
ELSE
BEGIN
    IF @PageIndex = @PageCount - 1
    BEGIN
       SET @SQLSTR =N'SELECT * FROM ( SELECT TOP ' + STR(@TOPCOUNT) +
       ' * FROM dbo.customers ORDER BY CustomerID ASC) T ORDER BY CustomerID DESC'
    END
    ELSE
    BEGIN
       SET @SQLSTR =N' SELECT TOP '+STR(@PageSize)+'* FROM (SELECT TOP ' + STR(@TOPCOUNT) +
       ' * FROM dbo.customers ORDER BY CustomerID ASC) T ORDER BY CustomerID DESC'
    END
END
/*执行*/
EXEC (@SQLSTR)
GO


带参数的分页
 
CREATE    PROCEDURE up_pagecutSample3
    @PageIndex INT, /*@PageIndex从计数,0为第一页*/
    @PageSize  INT, /*页面大小*/
    @RecordCount INT OUT, /*总记录数*/
    @PageCount INT OUT, /*页数*/
    @CustomerID NVARCHAR(5) /*查询条件*/
AS
/*获取记录数*/
SELECT @RecordCount = COUNT(0) FROM dbo.customers
/*计算页面数据*/
SET @PageCount = CEILING(@RecordCount * 1.0 / @PageSize)
/*TOP记录数*/
DECLARE @TOPCOUNT INT
SET @TOPCOUNT = @RecordCount - @PageSize * @PageIndex
DECLARE @SQLSTR NVARCHAR(1000)
IF @PageIndex = 0 OR @PageCount <= 1
BEGIN
    SET @SQLSTR =N'SELECT TOP '+STR(@PageSize)+
    ' * FROM dbo.customers WHERE CustomerID LIKE @CustomerID  ORDER BY CustomerID DESC'
END
ELSE
BEGIN
    IF @PageIndex = @PageCount - 1
    BEGIN
       SET @SQLSTR =N'SELECT * FROM ( SELECT TOP ' + STR(@TOPCOUNT) +
       ' * FROM dbo.customers CustomerID LIKE @CustomerID ORDER BY CustomerID ASC) T ORDER BY CustomerID DESC'
    END
    ELSE
    BEGIN
       SET @SQLSTR =N' SELECT TOP '+STR(@PageSize)+'* FROM (SELECT TOP ' + STR(@TOPCOUNT) +
       ' * FROM dbo.customers CustomerID LIKE @CustomerID ORDER BY CustomerID ASC) T ORDER BY CustomerID DESC'
    END
END
SELECT @CustomerID = N'%' + @CustomerID + N'%'
/*执行*/
EXEC sp_executesql @SQLSTR,N'@CustomerID NVARCHAR(5)',@CustomerID
GO


 使用临时表实现分页
create   PROC up_pagecutSample
 @pagesize INT,
 @page INT
AS
 DECLARE @ks INT
 DECLARE @str VARCHAR(200)
 SET @ks=@pagesize*(@page-1)
 IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[temp_table91]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
 BEGIN
  SELECT * INTO temp_table91 FROM dbo.customers ORDER BY CustomerID DESC
  SET rowcount @pagesize
  SET @str='select * from temp_table91 where CustomerID not in (select top '+str(@ks)+' CustomerID from temp_table91)'
  EXECUTE(@str)
  DROP TABLE temp_table91
 END
GO

5月14日

Reporting Services

Reporting Services 是基于服务器的全面解决方案,可用于创作、管理和提供基于纸稿的报表以及基于 Web 的交互式报表。
web服务器注册asp.net/visual studio2003/sql server200
服务端运行环境
web服务器注册asp.net/sql server200
1月26日

DoNet使用存储过程操作数据库

例子一 带输入参数返回记录集
要用的存储过程up_ListReply
 CREATE PROC dbo.up_ListReply
 @ID INT
AS
SET NOCOUNT ON
 SELECT
 A.f_Rid,
 A.f_Rname,
 A.f_Rcontent,
 A.f_Rip,
 A.f_Radddate,
 B.f_Uname,
 B.f_UHeadImg
 FROM
 dbo.tbl_reply AS A INNER JOIN dbo.tbl_Users
 AS B ON A.f_Rusername=B.f_Uname
 WHERE A.f_Tid=@ID
GO
程序页
 

<%@ Page Language="C#" ContentType="text/html" ResponseEncoding="utf-8" Debug="true" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="C#" runat="server">
void Page_Load(Object src,EventArgs e){
BindGrid();
}
void BindGrid() {

SqlConnection myConnection = new SqlConnection(ConfigurationSettings.AppSettings["MyConn2"]);
/*SqlDataAdapter myDataAdapter = new SqlDataAdapter("dbo.up_getAllUserData", myConnection);
myDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;

DataSet ds = new DataSet();
myDataAdapter.Fill(ds, "db");

Rep.DataSource = ds.Tables["db"].DefaultView;
Rep.DataBind();*/

myConnection.Open();

SqlCommand myCommand = new SqlCommand();
myCommand.Connection = myConnection;
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.CommandText = "dbo.up_ListReply";

myCommand.Parameters.Add("@ID", SqlDbType.Int);
myCommand.Parameters["@ID"].Value = Convert.ToInt32("12");
/*
SqlParameter myParam = myCommand.Parameters.Add("@ID", SqlDbType.Int);
myParam.Direction = ParameterDirection.Input;
myParam.Value = Convert.ToInt32("12");
*/
SqlDataReader myDataReader = myCommand.ExecuteReader();
Rep.DataSource = myDataReader;
Rep.DataBind();
}
</script>
<title>DB_Access_test11</title>
</head>
<body >
<form runat="server">
<ASP:Repeater id="Rep" runat="server">

<HeaderTemplate>
<h1>List Reply</h1>
<h1>Use Command/DataReader/Repeater_Control PageHeader</h1>
</HeaderTemplate>

<ItemTemplate>
<p style="font-size:12px">
ID:<font color="#0000FF"><%# DataBinder.Eval(Container.DataItem, "f_Rid") %></font>&nbsp;&nbsp;&nbsp;
TopicName:<font color="#FF0000"><%# DataBinder.Eval(Container.DataItem, "f_Rname") %></font>&nbsp;&nbsp;&nbsp;
UserName:<font color="#DFA894"><%# DataBinder.Eval(Container.DataItem, "f_Uname") %></font>&nbsp;&nbsp;&nbsp;
</p>
<p style="font-size:12px">
RegisterDate:<font color="#DFA894"><%# DataBinder.Eval(Container.DataItem, "f_Radddate") %></font>&nbsp;&nbsp;&nbsp;
Ip:<font color="#DFA894"><%# DataBinder.Eval(Container.DataItem, "f_Rip") %></font>&nbsp;&nbsp;&nbsp;
</p>
</ItemTemplate>

<alternatingitemtemplate>
<p style="font-size:12px">
ID:<font color="#0000FF"><%# DataBinder.Eval(Container.DataItem, "f_Rid") %></font>&nbsp;&nbsp;&nbsp;
TopicName:<font color="#00FF00"><%# DataBinder.Eval(Container.DataItem, "f_Rname") %></font>&nbsp;&nbsp;&nbsp;
UserName:<font color="#00CC99"><%# DataBinder.Eval(Container.DataItem, "f_Uname") %></font>&nbsp;&nbsp;&nbsp;
</p>
<p style="font-size:12px">
RegisterDate:<font color="#00CC99"><%# DataBinder.Eval(Container.DataItem, "f_Radddate") %></font>&nbsp;&nbsp;&nbsp;
Ip:<font color="#00CC99"><%# DataBinder.Eval(Container.DataItem, "f_Rip") %></font>&nbsp;&nbsp;&nbsp;
</p>
</alternatingitemtemplate>

<separatortemplate>
<div align="left">---------------------------------------------------------------------------------</div>
</separatortemplate>

<FooterTemplate>
<h2>All User Record PageFooter</h2>
</FooterTemplate>
</ASP:Repeater>
</form>
</body>
</html>


例子二 带输入参数输出参数
要用的存储过程up_getUserByUname
 CREATE PROCEDURE dbo.up_getUserByUname
(@uname NVARCHAR (20),@isvalid TINYINT OUTPUT)
--According username query user is exists根据用户名查询是否存在用户
AS
SET NOCOUNT ON
IF exists(SELECT f_Uid FROM tbl_users WHERE f_Uname=@uname)
SELECT @isvalid=1
ELSE
SELECT @isvalid=0
GO
程序页
<%@ Page Language="C#" ContentType="text/html" ResponseEncoding="utf-8" Debug="true" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="C#" runat="server">
void Page_Load(Object src,EventArgs e){
BindGrid();
}
void BindGrid() {

SqlConnection myConnection = new SqlConnection(ConfigurationSettings.AppSettings["MyConn2"]);
/*SqlDataAdapter myDataAdapter = new SqlDataAdapter("dbo.up_getAllUserData", myConnection);
myDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;

DataSet ds = new DataSet();
myDataAdapter.Fill(ds, "db");

Rep.DataSource = ds.Tables["db"].DefaultView;
Rep.DataBind();*/

myConnection.Open();
string uid;
int reVal;
uid = Request.QueryString["uid"].Trim().ToString();
SqlCommand myCommand = new SqlCommand();
myCommand.Connection = myConnection;
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.CommandText = "dbo.up_getUserByUname";

myCommand.Parameters.Add("@uname", SqlDbType.NVarChar, 20);
myCommand.Parameters.Add("@isvalid", SqlDbType.TinyInt);
myCommand.Parameters["@uname"].Value = uid;
myCommand.Parameters["@isvalid"].Direction = ParameterDirection.Output; //if return parameter ParameterDirection.ReturnValue

myCommand.ExecuteNonQuery();

reVal = Convert.ToInt32(myCommand.Parameters["@isvalid"].Value);
/*
SqlParameter myParam = myCommand.Parameters.Add("@uname", SqlDbType.NVarChar, 20);
myParam.Direction = ParameterDirection.Input;
myParam.Value = uid;

myParam = myCommand.Parameters.Add("@isvalid", SqlDbType.TinyInt);
myParam.Direction = ParameterDirection.Output;

myCommand.ExecuteNonQuery();

reVal = Convert.ToInt32(myParam.Value);
*/
if (reVal == 1){
result.Text = "found [" + uid + "] user";
}else if(reVal == 0){
result.Text = "not found user";
}
}
</script>
<title>DB_Access_test16</title>
</head>
<body>
<asp:Label ID="result" runat="server" BorderColor="#0000FF"/>
</body>
</html>

1月23日

使用.Net Framework绘制饼图

主要使用类库与结构
System.Drawing.Graphics
System.Drawing.Rectangle

代码如下

<%@ Page Language="C#" ContentType="text/html" ResponseEncoding="utf-8" Debug="true" %>
<!-- for .Net Framework 2.0 -->
<%@ Import Namespace="System.Drawing" %>
<script runat="server" language="c#">
 void Page_Load(object sender, EventArgs e){
  Bitmap image = new Bitmap(440,300);
  Graphics g = Graphics.FromImage(image);
  
  g.Clear(Color.White);
  
  Rectangle outline = new Rectangle(10, 10, 420, 240);
  
  g.DrawEllipse(new Pen(Color.Black, 4f), outline);

  //create data
  int[] b = new int[]{1565, 486, 5896, 1449};

  float count = b[0] + b[1] + b[2] + b[3];
  float[] c = new float[]{(b[0]/count), (b[1]/count), (b[2]/count), (b[3]/count)};
  float[] a = new float[]{(360 * c[0]), (360 * c[1]), (360 * c[2]), (360 * c[3])};
  
  //make  area pie
  g.FillPie(new SolidBrush(Color.Red), outline, 0f, a[0]);
  g.FillPie(new SolidBrush(Color.Yellow), outline, a[0], a[1]);
  g.FillPie(new SolidBrush(Color.Blue), outline, (a[0] + a[1]), a[2]);
  g.FillPie(new SolidBrush(Color.Green), outline, (a[0] + a[1] + a[2]), a[3]);
  
  //make color note start---
  g.DrawRectangle(new Pen(Color.Black, 1f), new Rectangle(10, 260, 10, 10));
  g.FillRectangle(new SolidBrush(Color.Red), 10, 260, 10, 10);
  g.DrawString("1item:" + b[0].ToString(), new Font("Black", 10), new SolidBrush(Color.Black), 25, 260);
  
  g.DrawRectangle(new Pen(Color.Black, 1f), new Rectangle(110, 260, 10, 10));
  g.FillRectangle(new SolidBrush(Color.Yellow), 110, 260, 10, 10);
  g.DrawString("2item:" + b[1].ToString(), new Font("Black", 10), new SolidBrush(Color.Black), 125, 260);
  
  g.DrawRectangle(new Pen(Color.Black, 1f), new Rectangle(210, 260, 10, 10));
  g.FillRectangle(new SolidBrush(Color.Blue), 210, 260, 10, 10);
  g.DrawString("3item:" + b[2].ToString(), new Font("Black", 10), new SolidBrush(Color.Black), 225, 260);
  
  g.DrawRectangle(new Pen(Color.Black, 1f), new Rectangle(310, 260, 10, 10));
  g.FillRectangle(new SolidBrush(Color.Green), 310, 260, 10, 10);
  g.DrawString("4item:s" + b[3].ToString(), new Font("Black", 10), new SolidBrush(Color.Black), 325, 260);
  //make color note end---
  
  //mark string
  g.DrawString(".Net Drawing", new Font("Arial Black", 20), new SolidBrush(Color.White), 100, 80);
  
  image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
  //Response.Write(a[0]+"/"+a[1]+"/"+a[2]+"/"+a[3]);
  //Response.Write((b[0]/(float)count*100));
  Response.ContentType="Image/Gif";
 }
</script>

正则表达式

  正则表达式(Regular Expression)是一种可以用于模式匹配和替换的强有力的工具。我们可以在几乎所有的基于UNIX系统的工具中找到正则表达式的身影,例如,vi编辑器, Perl或PHP脚本语言,以及awk或sed shell程序等。此外,象Javascrīpt这种客户端的脚本语言也提供了对正则表达式的支持。由此可见,正则表达式已经超出了某种语言或某个系统的局限,成为人们广为接受的概念和功能。
  正则表达式可以让用户通过使用一系列的特殊字符构建匹配模式,然后把匹配模式与数据文件、程序输入以及WEB页面的表单输入等目标对象进行比较,根据比较对象中是否包含匹配模式,执行相应的程序。
举例来说,正则表达式的一个最为普遍的应用就是用于验证用户在线输入的邮件地址的格式是否正确。如果通过正则表达式验证用户邮件地址的格式正确,用户所填写的表单信息将会被正常处理;反之,如果用户输入的邮件地址与正则表达的模式不匹配,将会弹出提示信息,要求用户重新输入正确的邮件地址。由此可见正则表达式在WEB应用的逻辑判断中具有举足轻重的作用。
基本语法
  在对正则表达式的功能和作用有了初步的了解之后,我们就来具体看一下正则表达式的语法格式。
正则表达式的形式一般如下,其中正则表达式直接量定义在位于“/”定界符之间的部分就是将要在目标对象中进行匹配的模式。用户只要把希望查找匹配对象的模式内容放入“/”定界符之间即可。

var pattern = /s$/;                   //定义一个表达式
  用构造函数RegExp定义正则表达式
var pattern = new RegExp("s$");      //使用RegExp定义一个表达式

特殊元素含义:

1.非字母字符的直接量

    字符                    匹配

    字母数字字符          自身

    \o                  NUL字符(对应\u0000

    \t                  制表符(\u0009

    \n                  换行符(\u000A

    \v                  垂直制表符(\u000B

    \f                  换页符(\u000C

    \r                  回车(\u000D

    \xnn                由十六进制数nn指定的拉丁字符,例如,\x0A等价于\n

    \uxxxx              由十六进制xxxx指定的Unicode字符,例如,\u0009等价于\t

    \cX                 控制字符^X,例如,\cJ等价于\n


2.特殊含义字符

       ^ $ . * + ? = ! : | \ / ( ) [ ] { }

       在匹配这些特殊含义字符本身的含义时,要在前面加\,如任何包含\的字符串的正则表达式为:/\\/


3.字符类直接量

   字符                匹配

    […]                位于括号内的任意字符

    [^…]               不在括号内的任意字符

    .                  除换行符和其他Unicode行中止符之外的任意字符

    \w                 任何ASCII单字字符,等价于[a-zA-Z0-9_]

    \W                 任何ASCII非单字字符,等价于[^a-zA-Z0-9_]

    \s                 任何Unicode空白符

    \S                 任何非Unicode空白符

    \d                 任何ASCII数字,等价于[0-9]

    \D                 除了ASCII数字之外的任何字符,等价于[^0-9]

    [\b]               退格直接量(特例)


4.重复字符

    字符               匹配

    {n,m}              匹配前一项至少n次,但是不能超过 m

   {n,}                  匹配前一项n次,或更多次

    {n}                匹配前一项恰好n

    ?                  匹配前一项0次或1次,也就是说前一项可选,等价于{0,1}

    +                  匹配前一项1次或多次,等价于{1,}

    *                  匹配前一项0次或多次,等价于{0,}

    非贪婪的重复:在匹配模式后面加一个问号,如/a+?/只匹配字符串的第一个字母a


5.选择、分组和引用字符

    字符              含义

    |                 选择,匹配的是该符号左边的子表达式或右边的子表达式

    (…)               组合,将几个项目组合为一个单元,这个单元可由*+?|组成

    (?:…)             只组合,把项目组合到一个单元,但是不记忆与该组匹配的字符

    \n                和第n个分组第一次匹配的字符相匹配,组是括号中的子表达式

(可能是嵌套的),组号是从左到右计数的左括号数,以(?:形式

分组的组不编码


6字符

    字符              含义

    ^                匹配字符串的开头,在多行检索中,匹配一行的开头

    $                匹配字符串的结尾,在多行检索中,匹配一行的结尾

    \b               匹配一个词语的边界

    \B               匹配非词语边界字符

    (?=p)            正向前声明,要求接下来的字符都与模式p匹配

    (?!p)            反向前声明,要求接下来的字符不与模式p匹配


7.标志字符

    字符              含义

    i                执行大小写不敏感的匹配

    g                执行全局匹配,寻找所有的匹配,不在找到第一个匹配后停止

    m                多行模式,结合^$使用(Supported in Javascrīpt1.5)


用于模式匹配的String方法:searchreplacematchsplit

用于模式匹配的RegExp方法:exectest

/\w{6}/.test("abcdef");                   //test用例
匹配return true否者为false
"Javascrīpt".search(/scrīpt/i);     //search用例 匹配return true否者为false

正字表达式举例:

/s$/                                匹配以字母s结尾的字符串

/\\/                                匹配包含反斜杠\的字符串

/[abc]/                             匹配字母“a”、“b”、“c”中的任何一个字母

/[a-z]/                             匹配拉丁字母集中任何小写字母

/[\u0400-\u04FF]/                   匹配所有的Cyrillic字符

/[\s\d]/                            匹配任意空白字符或数字

/\d{2,4}/                           匹配与24之间的数字

/\w{3}\d?/                           匹配三个字符一个数字

/\s+java\s+/                        匹配字符串java,切该串前后可以有一个或多个空格

/[^”]*/                             匹配零个或多个非引号字符

/ab|cd|ef/                          匹配字符串ab或者cd又或者ef

/\d{3}|[a-z]{4}/                    匹配一个三位数字或者四个小写字母

/java(scrīpt)?/                     匹配字符串java,其后可以有scrīpt也可以没有

/(ab|cd)+|ef/                       匹配可以是字符串ef,也可以是字符串ab或者cd的一次或多次

/Java(?!scrīpt)([A-Z]\W*)/          匹配Java跟随一个大写字母和任意多个ASCII字符,但是不能跟随scrīpt

/Java$/im                           JavaJava\nis fun匹配

/^\w{4,8}$/                         匹配4~8个字母数字的组合
/^.{4,8}$/                               
匹配4~8个任意字符的组合

/^\w+?@\w+\.\w{2,3}$/                     匹配E-mail格式 如wwwwww@wwwwwww.www

1月15日

使用DotNet来制作简单RSS频道

技术:ASP.Net/C#/XML
平台:IIS/.Framework1.0/MS SQL SERVER/IE or FireFox

使用RSS v2.0文档结构如下

<?xml version="1.0" encoding="utf-8" ?>
<rss version="2.0">
    <channel>
        <title/><link/><language/><docs/><descrīption/><copyright/><generator/><lastBuildDate/><ttl/>
        <image>
            <url/><title/><link/>
        </image>
        <item>
            <title/><link/>            
            <descrīption>                     
                <![CDATA[]]>               
            </descrīption>
            <category/><author/><pubDate/>
        </item>
    </channel>
</rss>

格式必须按照XML规范来写
RSS2.0参考文献: http://blogs.law.harvard.edu/tech/rss

定义读取RSS信息的存储过程

CREATE PROCEDURE [dbo].[up_ListTopic]        --list topic record 列出留言主题
AS
SET NOCOUNT ON
SET XACT_ABORT ON
    BEGIN TRANSACTION
    SELECT
    A.f_Tid,                --index 0
    A.f_Tname AS [标题:],            --index 1
    A.f_Tcontent AS [主题内容:],        --index 2
    A.f_Tip AS [留言者IP:],            --index 3
    A.f_Tadddate AS [留言日期:],        --index 4
    B.f_Uname AS [留言用户:],        --index 5
    A.f_ReplyHit AS [回复数:]        --index 6
    FROM dbo.tbl_topic AS A
    INNER JOIN dbo.tbl_Users AS B
    ON A.f_Uid=B.f_Uid
    ORDER BY A.f_Tadddate DESC
    COMMIT TRAN
GO

这里只用了这几个字段f_Tid, f_Tname, f_Tcontent, f_Tadddate, f_Uname

下面便是RSS生成的dotnet_rss.aspx

<%@ Page Language="C#" ContentType="application/xml" Debug="true" ResponseEncoding="utf-8" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script language="C#" runat="server">
    void Page_Load(Object src, EventArgs e){
        SqlConnection myConnection = new SqlConnection();        
        try{
            myConnection.ConnectionString="server=127.0.0.1;database=BBSDB;uid=sa;pwd=''";
            myConnection.Open();
            
            SqlCommand myCommand = new SqlCommand();
            myCommand.Connection = myConnection;
            myCommand.CommandType = CommandType.StoredProcedure;
            myCommand.CommandText = "[dbo].[up_listTopic]";
            
            SqlDataReader myDataReader = myCommand.ExecuteReader();        
                    
            //-----------make head detail-----------------
            StringBuilder xmlhead = new StringBuilder();    
            xmlhead.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
            xmlhead.Append("<rss version=\"2.0\">\n");
            xmlhead.Append("\t<channel>\n");
            xmlhead.Append("\t\t<title>MyBBS RSS Channel</title>\n");
            xmlhead.Append("\t\t<link>http://192.168.0.44/thebbs</link>\n");
            xmlhead.Append("\t\t<language>zh-cn</language>\n");
            xmlhead.Append("\t\t<docs>MyBBS RSS Center</docs>\n");
            xmlhead.Append("\t\t<descrīption>Latest 20 threads of all forums</descrīption>\n");
            xmlhead.Append("\t\t<copyright>Copyright(C) MyBBS</copyright>\n");
            xmlhead.Append("\t\t<generator>none</generator>\n");
            xmlhead.Append("\t\t<lastBuildDate>" + DateTime.Now + "</lastBuildDate>\n");
            xmlhead.Append("\t\t<ttl>90</ttl>\n");
            xmlhead.Append("\t\t<image>\n");
            xmlhead.Append("\t\t\t<url>http://127.0.0.1/thebbs/smile.gif</url>\n");
            xmlhead.Append("\t\t\t<title>MyBBS</title>\n");
            xmlhead.Append("\t\t\t<link>http://127.0.0.1/thebbs</link>\n");
            xmlhead.Append("\t\t</image>\n");
            
            //-----------make item-----------------        
            StringBuilder xmlitem = new StringBuilder();
            string descrīption = "";
            int i, num;
            num = 1;
            while(myDataReader.Read()){
                //-----------read 20 record-----------------
                if (num > 20) break;
                num++;
                descrīption = myDataReader[2].ToString();
                if (descrīption.Length < 300)
                    i = descrīption.Length;
                else
                    i = 300;            
                descrīption = descrīption.Substring(0, i);
                xmlitem.Append("\t\t<item>\n");
                xmlitem.Append("\t\t\t<title>" + myDataReader[1].ToString() + "</title>\n");
                xmlitem.Append("\t\t\t<link>http://127.0.0.1/thebbs/topic.aspx?Tid=" + myDataReader[0].ToString() + "</link>\n");
                xmlitem.Append("\t\t\t<descrīption><![CDATA[" + descrīption + "]]></descrīption>\n");
                xmlitem.Append("\t\t\t<category>none</category>\n");
                xmlitem.Append("\t\t\t<author>" + myDataReader[5].ToString() + "</author>\n");
                xmlitem.Append("\t\t\t<pubDate>" + myDataReader[4].ToString() + "</pubDate>\n");
                xmlitem.Append("\t\t</item>\n");
            }
            myConnection.Close();
    
            //-----------make footer-----------------
            StringBuilder xmlfooter = new StringBuilder();        
            xmlfooter.Append("\t</channel>\n</rss>");
            
            //-----------Output Data-----------------
            Response.Write(xmlhead);
            Response.Write(xmlitem);
            Response.Write(xmlfooter);
        }catch(Exception ex){

            //-----------can not find DB process-----------------
            Response.Write("<ErrorMsg>Connection Database Error...</ErrorMsg>");            
        }
    }
</script>

DotNET2.0可以用CodeFile将Script代码隐藏以来 Page部分如下
<%@ Page Language="C#" ContentType="application/xml" Debug="true" ResponseEncoding="utf-8" Inherits="MyRss" CodeFile="DotNet_RSS.aspx.cs" %>
Inherits为类名 CodeFile为隐藏代码
 
DotNet_RSS.aspx.cs腰包含的类包如下

using System;
using System.Text.StringBuilder;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data;
using System.Data.SqlClient;
public partial class  MyRss : Page{
        void Page_Load(Object src, EventArgs e){
               MakeRss();
        }
        public void MakeRss(){
               //原中dotnet_rss.aspx的代码段
        }
}

初始AJAX简单实例

使用技术Javascrīpt/AJAX/ASP
需要平台:IIS/IE or FireFox客户端

例子:在文本框中输入E文时会给出匹配E文提示

ajax.html 执行ajax页面

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>AJAX TEST</title>
</head>
<body>
    <scrīpt language="javascript">
    <!--
    var xmlHttp;
    function showHint(){                    //set execute ajax object
        var str = document.getElementById('txt1').value;
        if (str.length > 0)    {
            var url = "ajax_do.asp?q=" + str;
            document.getElementById("txtInner").innerHTML = 'Now Loading...';
            xmlHttp = GetXmlHttpObject(stateChanged);      //send ajax request
            xmlHttp.open("GET", url , true);
            xmlHttp.send(null);
        }else{
            document.getElementById("txtInner").innerHTML = "";
        }
    }
    function stateChanged(){                    //if ajax object active done Output data
        if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete"){
            document.getElementById("txtInner").innerHTML = xmlHttp.responseText;
        }
    }
    function GetXmlHttpObject(handler){        //create Ajax object function
        var ōbjXmlHttp = null;
        if (navigator.userAgent.indexOf("Opera") >= 0){
            alert("This example doesnt work in Opera");
            return;
        }
        if (navigator.userAgent.indexOf("MSIE") >= 0){
            var strName = "Msxml2.XMLHTTP";
            if (navigator.appVersion.indexOf("MSIE 5.5") >= 0){
                strName = "Microsoft.XMLHTTP";
            }
            try{
                ōbjXmlHttp = new ActiveXObject(strName);
                objXmlHttp.onreadystatechange = handler;
                return objXmlHttp;
            }catch(e){
                alert("Error. scrīpting for ActiveX might be disabled");
                return;
            }
        }
        if (navigator.userAgent.indexOf("Mozilla") >= 0){
            ōbjXmlHttp = new XMLHttpRequest();
            objXmlHttp.onload = handler;
            objXmlHttp.onerror = handler;
            return objXmlHttp;
        }
    }
    -->
    </script>
    <form id="Fm">
        First Name:<input type="text" id="txt1" onkeyup="showHint();">
    </form>
    <p>Suggestions: <span id="txtInner"></span></p>
</body>
</html>


ajax_do.asp 处理发送的请求页面

<%@LANGUAGE="VBscrīpt" CODEPAGE="65001"%>
<%
dim a(30)
a(1)="Anna"
a(2)="Brittany"
a(3)="Cinderella"
a(4)="Diana"
a(5)="Eva"
a(6)="Fiona"
a(7)="Gunda"
a(8)="Hege"
a(9)="Inga"
a(10)="Johanna"
a(11)="Kitty"
a(12)="Linda"
a(13)="Nina"
a(14)="Ophelia"
a(15)="Petunia"
a(16)="Amanda"
a(17)="Raquel"
a(18)="Cindy"
a(19)="Doris"
a(20)="Eve"
a(21)="Evita"
a(22)="Sunniva"
a(23)="Tove"
a(24)="Unni"
a(25)="Violet"
a(26)="Liza"
a(27)="Elizabeth"
a(28)="Ellen"
a(29)="Wells"
a(30)="Vicky"
q=request.querystring("q")
if len(q)>0 then
    hint=""
    for i=1 to 30
        x1=ucase(mid(q,1,len(q)))
        x2=ucase(mid(a(i),1,len(q)))
            if x1=x2 then
                if hint="" then
                    hint=a(i)
                else
                    hint=hint & " , " & a(i)
                end if
            end if
    next
end if
if hint="" then
    response.write("<font color=#FF0000>no suggestion</font>")
else
    response.write(hint)
end if
%>

设置好路径后用浏览器访问ajax.html在文本框中输入E文....

还可以下一个prototype.js包里面封装了ajax的功能,我们可以很方便使用它来简化代码
prototype.js包含进ajax.html后原先的脚本代码全改成如下

<script language="javascript">
<!--
function showHint(){
    var param=$('txt1').value;
    if (param.length > 0){
        $('txtInner').innerHTML='On Loading...';
        new Ajax.Updater("txtInner", 'ajax_do2.asp',{method:'get', parameters:'q='+param});
        //new Ajax.Request('ajax_do2.asp',{asynchronous:false, method:'post', postBody:'q='+param, onSuccess:handlerFunc});
    }else{
        $('txtInner').innerHTML='';
    }
}
-->
</script>
10月31日

从数据库中随机读取记录

DB2
SELECT *
FROM mytable
ORDER BY rand() fetch first 10 rows only

MySQL
SELECT *
FROM mytable
ORDER BY rand() limit 10

PostgreSQL
SELECT *
FROM mytable
ORDER BY random() limit 10

Oracle
SELECT *
FROM (
SELECT *
FROM mytable
ORDER BY dbms_random.value()
)
WHERE rownum <= 10
 注:dbms_random包需手动安装

SQL Server
SELECT TOP 10 *
FROM mytable
ORDER BY newid()
8月11日

ASP+JavaScript 两层菜单联动

建立Table
CREATE TABLE main_list
( id INT PK,
 names NAVRCHAR(20)
)
CREATE TABLE sub_list
(
 id INT PK,
 mainid INT FK_main_list,
 names NVARCHAR(20)
)

ASP 代码

<!--#include file="conn.asp"-->
<%
Dim rs, count, selclass
set rs=server.createobject("adodb.recordset")
%>
<form name="Fm" method="post" action="">
<%rs.open "select * from sub_list",conn,1,1%>
<script language = "JavaScript">
 var onecount;
 onecount=0;
 subcat = new Array();
<%
count = 0
do while not rs.eof
%>
 subcat[<%=count%>] = new Array("<%= trim(rs("name"))%>","<%= rs("mainid")%>","<%= trim(rs("id"))%>");
<%
count = count + 1
rs.movenext
loop
rs.close
%>
 onecount=<%=count%>;

 function changelocation(locationid){
  document.Fm.selsubid.length = 0;

  var locationid=locationid;
  var i;
  for (i=0;i < onecount; i++){
   if (subcat[i][1] == locationid){
    document.Fm.selsubid.options[document.Fm.selsubid.length] = new Option(subcat[i][0], subcat[i][2]);
   }
  }
 }
</script>
<table>
 <tr>
  <td>
<%
rs.open "select * from main_list",conn,1,1
if rs.eof and rs.bof then
 response.write "can't link database"
 response.end
else
%>
 Mian Category:
 <select name="selmainid" size="1" id="selmainid" onChange="changelocation(document.Fm.selmainid.options[document.Fm.selmainid.selectedIndex].value)">
 <option value="0" selected>==Select==</option>
<%
selclass=rs("id")
do while not rs.eof
%>
 <option value="<%=rs("id")%>"><%=trim(rs("names"))%></option>
<%
rs.movenext
loop
end if
rs.close
%>
 </select>
 Sub Category:
 <select name="selsubid">
<%
rs.open "select * from sub_list where mainid="&selclass ,conn,1,1
if not(rs.eof and rs.bof) then
%>
 <option selected value="0">==Select==</option>
<% do while not rs.eof%>
 <option value="<%=rs("id")%>"><%=rs("names")%></option>
<% rs.movenext
loop
end if
rs.close
set rs = nothing
%>
 </select>
  </td>
 </tr>
</table>
</form>

7月21日

DBHelper数据库访问

DB Access Framework是开发的时候为了同一管理data access code而提高web application的ASP专用class component。

DB Helper是server side include, 所以不用安装或登陆能直接用。放在web application上然后在要用的ASP页面用下面的code来include

DBHelper 产生方法是和一般的class instance一样。用完后用nothing来清除。

DB Helper提供的方法和属性是

访问权限 方法/属性 参数表 返回类型 功能说明
public ExecSPReturnRS spName, params, connectionString Recordset 执行DB中保存的procedure
ExecSQLReturnRS strSQL, params, connectionString Recordset 执行SQL语句
ExecSP spName, params, connectionString   执行DB中保存的procedure如更新操作
ExecSQL strSQL, params, connectionString   执行SQL语句如更新操作
BeginTrans connectionString Connection 开始transaction
CommitTrans Connection   实行活动的transaction
RollbackTrans Connection   回滚活动的transaction
MakeParam PName,PType,PDirection,PSize,PValue Array Type 建立Params参数列
GetValue params, paramName Simple Variables 参数排列中选择特定的参数
Dispose     关闭内部的DefaultConnection,释放memory
private collectParams cmd,argparams(params)   提取数组参数列表,做Parameter,然后把那个数据Command加上去
DefaultConnString (这是属性string)   默认DB连接串
DefaultConnection (这是属性Connection)   默认Connection对象

* params为一个[N,4]的数组 例:params[0]内容为("@idx",adInteger,adParamInput,0,p_idx)

一个使用的ExecSPReturnRS例子

存储过程

Create procedure TestSP2
@Beginning_Date DateTime,
@Ending_Date DateTime,
@RecordCount int output
AS
SELECT Orders.ShippedDate, Orders.OrderID, "Order Subtotals".Subtotal,
DATENAME(yy,ShippedDate) AS Year
FROM Orders INNER JOIN "Order Subtotals" ON Orders.OrderID = "Order Subtotals".OrderID
WHERE Orders.ShippedDate Between @Beginning_Date And @Ending_Date

SELECT @RecordCount = @@rowcount

ASP代码

Set DBHelper = new clsDBHelper '建立dbhelper对象    
RecordCount = 0        '记录总数

'设置参数
Dim paramInfo(2)
paramInfo(0) = DBHelper.MakeParam("@Beginning_Date",adDate,adParamInput,0, "1998/01/01")
paramInfo(1) = DBHelper.MakeParam("@Ending_Date",adDate,adParamInput,0, "1998/03/01")
paramInfo(2) = DBHelper.MakeParam("@RecordCount",adInteger,adParamOutput,,0)

'执行ExecSPReturnRS返回Recordset
Set rs = DBHelper.ExecSPReturnRS("TestSP2", paramInfo, Nothing)

'@RecordCount Output结果
RecordCount = DBHelper.GetValue(paramInfo, "@RecordCount")

rs.Close

Set rs = Nothing

DBHelper.Dispose
Set DBHelper = Nothing

7月20日

ASP DB Image处理

要求数据库中存储图片的字段类型为长二进制数据 如:Image、OLEObject、LongRawBlob等
浏览器遇到<IMG>标志时,会根据设定的src属性来加载文件,这可能是一个图形文件或则是一个ASP页面。
如果是一个返回图片类型的二进制的ASP页面,需要指定content type可以采用"image/*"方式,也可根据图
片类型设置如"image/bmp"、"image/gif"、"image/jpeg"等。
ImageSize=objRs("Image").ActualSize '采用ActualSize方法读取数据块的大小
ImageData=objRs("Image").GetChunk(ImageSize)'采用GetChunk方法读取指定大小的数据块
Response.BinaryWrite ImageData '显示数据块由于设置content type为image所以显示的为图片
============================================================

showimage.asp

<%

if request("id")=Empty then response.end

response.Expires=0

response.Buffer=True
response.Clear

'建立数据连接略写..............

objConn.Open

strsql="SELECT image FROM [tbl_image] WHERE img_id="& trim(request("id"))

objRs strsql,objConn,3,1

if Not objRs.Eof Then

 response.contentType="image/*"

 ImageSize=objRs("Image").ActualSize

 ImageData=objRs("Image").GetChunk(ImageSize)

 response.BinaryWrite ImageData

end if

objRs.close

Set objRs=Nothing

%>


显示图片时设置标签如下
<img src="showimage.asp?id=图片ID" />
----------------------------------------------------------------
上传图片到数据库
上传时标签设置为enctype="multipart/form-data"方式
============================================================
formdata=request.binaryread(request.totalbytes)
bncrlf=chrB(13) & chrB(10)
divider=LeftB(formdata,clng(instrb(formdata,bncrlf))-1)
datastart=instrb(formdata,bncrlf & bncrlf)+4
dataend=instrb(datastart+1,formdata,divider)-datastart
Imagedata=midb(formdata,datastart,dataend)
===========================================================
以上代码是将图片数据从上传流中截取出来ImageData
objRs("Image").AppendChunk ImageData '采用AppendChunk方法将图片数据加到字段中

uploadimg.asp

<%

response.buffer=true

formsize=request.totalbytes

formdata=request.binaryread(formsize) 

bncrlf=chrB(13) & chrB(10) 

divider=leftB(formdata,clng(instrb(formdata,bncrlf))-1) 

datastart=instrb(formdata,bncrlf & bncrlf)+4 

dataend=instrb(datastart+1,formdata,divider)-datastart 

Imagedata=midb(formdata,datastart,dataend)

'建立数据连接略写..............

strsql="SELECT * FROM [[tbl_image]] where img_id is null"

objRs.Open strsql,connGraph,1,3 

objRs.addnew 

objRs("image").appendchunk Imagedata

objRs.update 

objRs.close 

set objRs=nothing  

%> 

如果是新建图片数据记录要在上边加objRs.addnew如果更新的话不用加

ASP DB连接

连接Access数据库方法1 OLE DB provider
===================================================
Set Conn = Server.CreateObject("ADODB.Connection")
Conn.ConnectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("dbname.mdb") &";"
Conn.Open()
//这里是用的相对路径 "dbname.mdb"与asp该页在同一目录
//带密码的数据库连接为
Conn.Provider = "Microsoft.Jet.OLEDB.4.0;Jet OLEDB:Database Password='password'"
Conn.Open Server.MapPath("dbname.mdb")
---------------------------------------------------
连接Access数据库方法2 调用Access驱动程序数据库连接为
===================================================
connstr="DRIVER={Microsoft Access Driver (*.mdb)};DBQ=" & Server.MapPath("dbname.mdb") & ";uid=;pwd=;"
set conn=Server.CreateObject("ADODB.Connection")
conn.ConnectionString=connstr
conn.Open()
---------------------------------------------------
连接Access数据库方法3 使用SYSTEM DSN连接
===================================================
set conn=Server.CreateObject("ADODB.CONNECTION")
conn.ConnectionString="DSN数据源名"
conn.Open()
---------------------------------------------------
连接Visual FoxPro数据库方法1
===================================================
connstr="SourceDB="&Server.MapPath("dbname.dbc")&";Driver={microsoft Visual Foxpro driver};SourceType=DBC;Exclusive=No;" "
set conn=Server.CreateObject("ADODB.Connection")
conn.ConnectionString=connstr
conn.Open()

连接SQL SERVER数据库方法1
===================================================
set conn=Server.CreateObject("ADODB.Connection")
conn.ConnectionString="Driver={sql server};server=nt_server;uid=sa;pwd=;database=dbname"
conn.Open()
---------------------------------------------------
连接SQL SERVER数据库方法2 使用ODBC的系统DSN进行SQL SERVER连接
===================================================
set conn=Server.CreateObject("ADODB.Connection")
conn.ConnectionString="dsn=dsn_name;uid=user_name;pwd=password"
conn.Open()
---------------------------------------------------
连接SQL SERVER数据库方法3 OLE DB provider
===================================================
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="SQLOLEDB;data source=machinename;initial catalog=dbname;userid=sa;password=pass;"
conn.Open()
---------------------------------------------------
连接Oracle数据库方法1
===================================================
set conn=Server.CreateObject("ADODB.Connection")
conn.ConnectionString="Driver={Microsoft ODBC For Oracle};server=oraclesever.world;uid=admin;pwd=pass;"
conn.Open()
连接Oracle数据库方法2 OLE DB provider
===================================================
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="OraOLEDB.Oracle;data source=dbname;user id=admin;password=pass;"
conn.Open()
 
*****************************************************************
还有采用UDL方式用文本编辑器建立一个DB.udl然后打开Db.udl文件设置如图

使用时如下

connstr="file name=" & Server.MapPath("DB.udl")

ASP(VB与DB)数据类型参照

ADO
DataType
Enum

ADO
DataType
Enum
Value

.NET
Framework

Visual
Basic
6.0

Access

SQL
Server

Oracle

adBigInt

20

Int64
SqlInt64
BigInt

Variant

 

BigInt

 

adBinary

128

Byte[]
SqlBinary
Binary

Variant

 

Binary
TimeStamp

Raw

adBoolean

11

Boolean
SqlBoolean
Boolean

Boolean

YesNo

Bit

 

adBSTR

8

String
BSTR

 

 

 

 

adChapter

136

(DataReader)

 

 

 

 

adChar

129

String 
SqlString
Char

String

 

Char

Char

adCurrency

6

Decimal
SqlMoney
Currency

Currency

Currency

Money
SmallMoney

 

adDate

7

DateTime
Date

Date

DateTime

 

 

adDBDate

133

DateTime
DBDate

 

 

 

 

adDBFileTime

137

DBFileTime

 

 

 

 

adDBTime

134

DateTime
DBTime

 

 

 

 

adDBTimeStamp

135

DateTime
SqlDateTime
DBTimeStamp

Date

DateTime

Datetime
 SmallDateTime

Date

adDecimal

14

Decimal
Decimal

Variant

 

 

Decimal

adDouble

5

Double
SqlDouble
Double

Double

Double

Float

Float

adEmpty

0

Empty

 

 

 

 

adError

10

External-Exception
Error

 

 

 

 

adFileTime

64

DateTime
Filetime

 

 

 

 

adGUID

72

Guid 
SqlGuid
Guid

Variant

ReplicationID

UniqueIdentifier

 

adIDispatch

9

Object
IDispatch

 

 

 

 

adInteger

3

Int32
SqlInt32
Integer

Long

 AutoNumber
 Integer
Long

Identity
Int

Int

adIUnknown

13

Object
IUnknown

 

 

 

 

adLongVarBinary

205

Byte[]
SqlBinary
LongVarBinary

Variant

OLEObject

Image

Long Raw
Blob

adLongVarChar

201

String
SqlString
LongVarChar

String

Memo
Hyperlink

Text

Long
Clob

adLongVarWChar

203

String
SqlString
LongVarWChar

String

Memo
Hyperlink

NText

NClob

adNumeric

131

Decimal
SqlDecimal
Numeric

Variant

Decimal

Decimal
Numeric

Decimal
Integer
Number
SmallInt

adPropVariant

138

Object
PropVariant

 

 

 

 

adSingle

4

Single
SqlSingle
SIngle

Single

Single

Real

 

adSmallInt

2

Int16,
SqlInt16
SmallInt

Integer

Integer

SmallInt

 

adTinyInt

16

Byte
TinyInt

 

 

 

 

adUnsignedBigInt

21

UInt64
UnsignedBigInt

 

 

 

 

adUnsignedInt

19

UInt32
UnsignedInt

 

 

 

 

adUnsignedSmallInt

18

UInt16
UnsignedSmallInt

 

 

 

 

adUnsignedTinyInt

17

Byte
SqlByte
UnsignedTinyInt

Byte

Byte

TinyInt

 

adUserDefined

132

 

 

 

 

 

adVarBinary

204

Byte[] 
SqlBinary
VarBinary

Variant

ReplicationID

VarBinary

 

adVarChar

200

String
SqlString
VarChar

String

Text

VarChar

VarChar

adVariant

12

Object
Variant

Variant

 

Sql_Variant

VarChar2

adVarNumeric

139

VarNumeric

 

 

 

 

adVarWChar

202

String
SqlString
VarWChar

String

Text

NVarChar

NVarChar2

adWChar

130

String
SqlString
WChar

String

 

NChar