top
Loading...
在config.web中保存數據庫連接串
在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>

討飯貓 翻譯自aspfree.com

北斗有巢氏 有巢氏北斗