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

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

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

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

Config.web

1<configuration>
2<appsettings>
3<add key="MyConn" value="server=localhost;uid=sa;pwd=mypassword;Database=somedatabase"></add>
4</appsettings>
5</configuration>

Somepage.aspx

1@ Import Namespace="System.Data" 
1@ Import Namespace="System.Data.SQL" 
 1<script language="VB" runat="server">   
 2  
 3Sub Page_Load(Src As Object, E As EventArgs)   
 4  
 5'This is the meat of calling the DSN out of the config.web   
 6  
 7'Setting a local variable to hold the connection string variable   
 8Dim MyConnection As SQLConnection   
 9Dim Config as HashTable   
10  
11'Setting a local variable to hold the connection string   
12Config = Context.GetConfig("appsettings")   
13MyConnection = New SQLConnection(Config("MyConn"))   
14  
15'Setting a command object to insert some data into a database   
16Dim MyCommand As SQLCommand   
17  
18dim parm1 as string = "SomeTextValue"   
19dim parm2 as string = "SomeTextValue2"   
20  
21Dim InsertCmd As String = "Insert into tablename values (@parm1, @parm2)"   
22  
23'Using the connection string   
24MyCommand = New SQLCommand(InsertCmd, MyConnection)   
25  
26MyCommand.Parameters.Add(New SQLParameter("@Parm1", SQLDataType.VarChar, 50))   
27MyCommand.Parameters("@Parm1").Value = Parm1   
28  
29MyCommand.Parameters.Add(New SQLParameter("@Parm2", SQLDataType.VarChar, 50))   
30MyCommand.Parameters("@Parm2").Value = Parm2   
31  
32MyCommand.ActiveConnection.Open()   
33MyCommand.Execute()   
34MyCommand.ActiveConnection.Close()   
35  
36End Sub   
37</script>
Published At
Categories with Web编程
Tagged with
comments powered by Disqus