当前位置: 首页 > 图文教程 > 网络编程 > ASP > 在config.web中保存数据库连接串

ASP
用PreRender解决DataGrid分页最后一页行数不满的排版问题
基于ASP的站内多值搜索
XLS与MDB文件格式互换全攻略
一个用ASP生成html的新方法
将指定的asp文件内容生成HTML文件
使用Session记录页面地址和实现页面返回功能
IIS6架设网站常见问题及症状举例答疑
ASP调用WEBSERVICE文档
用Asp获取Dll加密新闻内容
Access2000数据库80万记录通用快速分页类
如何防止ASP木马在服务器上运行
如何使用javascript来写ASP程序
用存储过程实现ASP对数据库访问
学会在ASP中使用存储过程
ASP中和星期有关的自定义函数
水晶报表打印单据时增加空行或空白行的示例脚本
ASP+Access莫名奇妙的sql语句错误解决
ASP获取客户端MAC地址
在ASP中执行Ping命令,并且返回结果
如何使用ASP建立虚拟的FTP服务器

ASP 中的 在config.web中保存数据库连接串


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-11-03   浏览: 47 ::
收藏到网摘: n/a

  在asp中有多种方法保存数据库连接串,asp+提供了另一种新方式:config.web。quickstart中的许多demo都是直接将连接串写在程序中。这对于demo用途是没有问题,但在实际使用中是不行的。

本文示范如何使用config.web来存储连接串。在每页asp.net中你只需用
调出来就可以直接使用了。这样做的好处一是安全,二是方便,改密码时只需改一个地方即可。

废话少说,这里就是code:(放在该application的根目录下)

Config.web
<configuration>
        <appsettings>
                <add key="MyConn" value="server=localhost;uid=sa;pwd=mypassword;Database=somedatabase"/>
        </appsettings>
</configuration>


Somepage.aspx
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQL" %>

<script language="VB" runat="server">

Sub Page_Load(Src As Object, E As EventArgs)

'This is the meat of calling the DSN out of the config.web

'Setting a local variable to hold the connection string variable
Dim MyConnection As SQLConnection
Dim Config as HashTable

'Setting a local variable to hold the connection string
Config = Context.GetConfig("appsettings")
MyConnection = New SQLConnection(Config("MyConn"))

'Setting a command object to insert some data into a database
Dim MyCommand As SQLCommand

dim parm1 as string = "SomeTextValue"
dim parm2 as string = "SomeTextValue2"

Dim InsertCmd As String = "Insert into tablename values (@parm1, @parm2)"

'Using the connection string
MyCommand = New SQLCommand(InsertCmd, MyConnection)

MyCommand.Parameters.Add(New SQLParameter("@Parm1", SQLDataType.VarChar, 50))
MyCommand.Parameters("@Parm1").Value = Parm1

MyCommand.Parameters.Add(New SQLParameter("@Parm2", SQLDataType.VarChar, 50))
MyCommand.Parameters("@Parm2").Value = Parm2

MyCommand.ActiveConnection.Open()
MyCommand.Execute()
MyCommand.ActiveConnection.Close()

End Sub
</script>