We need to connect the database to a separate configuration so that we can use the
1, create a new class file, the name is arbitrary, but it is best to end with handler, because to inherit IConfigurationSectionHandler
1 Public classConnhandler:iconfigurationsectionhandler2 {3 4 Const stringStrformat ="server={0};d atabase={1};uid={2};p wd={3}";5 6 7 #regionIConfigurationSectionHandler Members8 9 Public ObjectCreate (ObjectParentObjectConfigcontext, XmlNode node)Ten { OneHashtable TB =NewHashtable (); A - foreach(XmlNode xninchnode. ChildNodes) - { the if(xn. NodeType = =xmlnodetype.element) - {
Jhencrypt.decrypt is a custom decryption algorithm, and as for how you encrypt it, it's your business. - stringServre = Jhencrypt.decrypt (xn. SelectNodes ("Server")[0]. InnerText); - stringDatabase = Jhencrypt.decrypt (xn. SelectNodes ("Database")[0]. InnerText); + stringuser = Jhencrypt.decrypt (xn. SelectNodes ("User")[0]. InnerText); - stringPassword = jhencrypt.decrypt (xn. SelectNodes ("Password")[0]. InnerText); +Tb. Add (xn. Name,string. Format (Strformat, Servre, database, user, password)); A } at } - returnTB; - - } - - #endregion in}
2, you have seen, this needs to define an XML file, and then the XML file needs to have the server, database, user, password node, we temporarily named the XML file "Conndb.config"
1 <conndb>2 <DB>3 <Server>The DB instance to encrypt</Server>4 <Database>The database to encrypt</Database>5 <User>The user name to encrypt</User>6 <Password>The password to encrypt</Password>7 </DB>8 </conndb>
3. You should add a custom section to the Web. config
1 < configsections > 2 name = "Conndb" type = "Custom. Connhandler " /> 3 </ configsections > 4 < conndb configsource = "Conndb.config" />
The name of the newly created section must correspond to the name declared below, type is a namespace. Folder name (ignorable). Class name
The configsource of the section configuration sections that are declared below is the name of the new XML file
4. Use
When the page loads, it reads the contents of the Custom sections configuration section in Web. config, and then executes the custom handler create method to get the connection string contents from the XML into the Hashtable
We just use the following sentence to get the database connection string from the section.
Hashtable.synchronized ((Hashtable) configurationmanager.getsection ("conndb"));
Hashtable.synchronized is for thread safety reasons,
Of course, you can also use Configurationmanager.getsection ("Conndb") to get a single Object object into a string
Only if you have a child node in your XML that is under a parent node
Configure a stand-alone database connection configuration file