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

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

1<br/>
1<br/>

本文示范如何使用config.web来存储连接串。在每页asp.net中你只需用

1<br/>

调出来就可以直接使用了。这样做的好处一是安全,二是方便,改密码时只需改一个地方即可。

1<br/>
1<br/>

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

1<br/>
1<br/>

Config.web

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

Somepage.aspx

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

讨饭猫 翻译自aspfree.com

1<br/>
Published At
Categories with Web编程
Tagged with
comments powered by Disqus