Home Database Mysql Tutorial 用反射+配置文件实现数据库的访问

用反射+配置文件实现数据库的访问

Jun 07, 2016 pm 03:30 PM
reflection accomplish database access Configuration file

刚开始对配置文件的认识比较模式,按照书上讲的,往程序中添加一个App.config文件,然后添加System.configuration引用就可以了。但是真正去做的时候也遇到不少问题,小小的总结一下。 首先,为什么要使用配置文件呢? 我们在连接数据库的时候,需要有一个对

        刚开始对配置文件的认识比较模式,按照书上讲的,往程序中添加一个App.config文件,然后添加System.configuration引用就可以了。但是真正去做的时候也遇到不少问题,小小的总结一下。

       首先,为什么要使用配置文件呢?

       我们在连接数据库的时候,需要有一个对象来保存连接字符串,通常情况下这个字符串是写在程序代码中的,这样如果我们更换数据库访问时,我们还是要重新修改程序,这样是很不灵活的;其次,出于安全考虑,我们都知道SQL注入,攻击者通过输入特定字符修改SQL语句,从而获得一些比较私密的信息,危害数据库,看过曾经的一则新闻,12306网站存在SQL注入等多个漏洞,试想如果一旦被一些有心人士利用了,后果是不堪设想的。基于以上原因,我们引入了配置文件。

        其次,介绍一下配置文件的使用。

        我在重构机房收费系统时在两处使用了配置文件。

        第一处:保存连接数据的字符串。

        没有使用配置文件,是这样定义连接字符串的:

       

<span>Dim strCon As String = "Data Source=localhost;Initial Catalog=User;User ID=sa;Password=123456;"</span>
Copy after login

        现在我们要使用配置文件来保存连接字符串:

        ①在UI层中的添加一个“应用程序配置文件”,即App.configuration文件,一般是默认就用的不同添加。注意的是一定要添加在UI层,因为程序是从UI层开始读取的。配置文件的内容如下:

       

<span><configuration>
    <appsettings>        
       <add key="Constr" value="Data Source=localhost;Initial Catalog=User;User ID=sa;Password=123456"></add>
    </appsettings>
</configuration></span>
Copy after login

        然后在D层读取配置文件:

       

<span>Dim strCon As String = System.Configuration.ConfigurationSettings.AppSettings("Constr")</span>
Copy after login

        这样,如果我们需要更换数据库,直接更改连接配置文件中的字符串就可以了,不需要更改程序代码。

        第二处:在DBFactory工厂类中,实例化D层的Sqlserver类时。在App.config文件中再加上名为“DB”的key,并赋值,如下:

    

<span><configuration>
    <appsettings>
        <add key="DB" value="Sqlserver"></add>         
       <add key="Constr" value="Data Source=localhost;Initial Catalog=User;User ID=sa;Password=123456"></add>
    </appsettings>
</configuration></span>
Copy after login

        然后,在DBFactroy工厂类中,读取配置文件。

       

<span>    Dim strDB As String = ConfigurationSettings.AppSettings("DB")

    Public Shared Function CreateUserDAO() As IDAL.IUserInfo
        Dim ClassName As String
        ClassName = AssemblyName + "." + DB
        Return CType(Assembly.Load(AssemblyName).CreateInstance(ClassName), IDAL.IUserInfo)
    End Function</span>
Copy after login




Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Reflection mechanism implementation of interfaces and abstract classes in Java Reflection mechanism implementation of interfaces and abstract classes in Java May 02, 2024 pm 05:18 PM

The reflection mechanism allows programs to obtain and modify class information at runtime. It can be used to implement reflection of interfaces and abstract classes: Interface reflection: obtain the interface reflection object through Class.forName() and access its metadata (name, method and field) . Reflection of abstract classes: Similar to interfaces, you can obtain the reflection object of an abstract class and access its metadata and non-abstract methods. Practical case: The reflection mechanism can be used to implement dynamic proxies, intercepting calls to interface methods at runtime by dynamically creating proxy classes.

How to use reflection to access private fields and methods in golang How to use reflection to access private fields and methods in golang May 03, 2024 pm 12:15 PM

You can use reflection to access private fields and methods in Go language: To access private fields: obtain the reflection value of the value through reflect.ValueOf(), then use FieldByName() to obtain the reflection value of the field, and call the String() method to print the value of the field . Call a private method: also obtain the reflection value of the value through reflect.ValueOf(), then use MethodByName() to obtain the reflection value of the method, and finally call the Call() method to execute the method. Practical case: Modify private field values ​​and call private methods through reflection to achieve object control and unit test coverage.

Where is the win10 user profile? How to set the user profile in Win10 Where is the win10 user profile? How to set the user profile in Win10 Jun 25, 2024 pm 05:55 PM

Recently, many Win10 system users want to change the user profile, but they don’t know how to do it. This article will show you how to set the user profile in Win10 system! How to set up user profile in Win10 1. First, press the "Win+I" keys to open the settings interface, and click to enter the "System" settings. 2. Then, in the opened interface, click "About" on the left, then find and click "Advanced System Settings". 3. Then, in the pop-up window, switch to the "" option bar and click "User Configuration" below.

iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos Jul 18, 2024 am 05:48 AM

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

Detailed tutorial on establishing a database connection using MySQLi in PHP Detailed tutorial on establishing a database connection using MySQLi in PHP Jun 04, 2024 pm 01:42 PM

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

Security considerations and best solutions for golang reflection Security considerations and best solutions for golang reflection May 04, 2024 pm 04:48 PM

Reflection provides type checking and modification capabilities in Go, but it has security risks, including arbitrary code execution, type forgery, and data leakage. Best practices include limiting reflective permissions, operations, using whitelists or blacklists, validating input, and using security tools. In practice, reflection can be safely used to inspect type information.

How to handle database connection errors in PHP How to handle database connection errors in PHP Jun 05, 2024 pm 02:16 PM

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

How to use reflection to dynamically modify variable values ​​in golang How to use reflection to dynamically modify variable values ​​in golang May 02, 2024 am 11:09 AM

Go language reflection allows you to manipulate variable values ​​at runtime, including modifying Boolean values, integers, floating point numbers, and strings. By getting the Value of a variable, you can call the SetBool, SetInt, SetFloat and SetString methods to modify it. For example, you can parse a JSON string into a structure and then use reflection to modify the values ​​of the structure fields. It should be noted that the reflection operation is slow and unmodifiable fields cannot be modified. When modifying the structure field value, the related fields may not be automatically updated.

See all articles