盾怪网教程:是一个免费提供流行杀毒软件教程、在线学习分享的学习平台!

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

时间:2025/1/5作者:未知来源:盾怪网教程人气:

[摘要]在asp中有多种方法保存数据库连接串,asp+提供了另一种新方式:config.web。quickstart中的许多demo都是直接将连接串写在程序中。这对于demo用途是没有问题,但在实际使用中是...
在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>






关键词:在config.web中保存数据库连接串




Copyright © 2012-2018 盾怪网教程(http://www.dunguai.com) .All Rights Reserved 网站地图 友情链接

免责声明:本站资源均来自互联网收集 如有侵犯到您利益的地方请及时联系管理删除,敬请见谅!

QQ:1006262270   邮箱:kfyvi376850063@126.com   手机版