C # Programming - Method for connecting to the database

zhaozj2021-02-16  42

C # Programming - Method for connecting to the database

2 Keywords

System configuration file, connection string, form, component, inheritance, XML, reuse.

2 description

Connect the dynamic properties of the string through the system's configuration file settings (connected strings). A connection is implemented by the Inherit mechanism of the form (Component) (ie there is only one interface with the database throughout the system).

2 system configuration file

The system profile is an XML file called app.config, generated by .NET. In .NET, you can display two views of "XML" and "Data".

2 How to configure dynamic connection properties

1) Set the Connectionstring property of SqlConnect

2) Click to expand the DynamicProperties of SqlConnect

3) Click on DynamiCProperties' Connectionstring to pop up the following form, press "OK"

Open the app.config file can see the key and key value to join the configuration file.

4) You can only configure App.config when the software is published (modify the connection string).

2 How to inherit the form and components

Inheritance is an important mechanism for object-oriented, which allows the successor to share, access the inherited resources (attributes, methods, events, etc.), which is an important way to implement the reuse of the code.

1) Form inheritance

Create a new base form, add the connection properties in the form, and configure dynamic connection properties with the above method. Next, the new subs class inherits the form (add new item-add inherited form), select the base class form in the Inherit Instrument.

2) Component inheritance

Since there is no inheritance component, the component inherits is different from the form inheritance. New parent class and subclass components (add new items - add inheritance components) and then manually set the inheritance relationship of components. As follows (see 11 lines of inheritcomponent.cs):

/ / Specify the base class of InheritComponent as SampleConnectDatabase.baseComponent

Public class inheritcomponent: SampleConnectDatabase.basecomponent

{

}

2 How to test database connections

Connection strings are typically set correctly (set up the configuration file) if you still need to detect if you correctly connect the database, you can run a Command, which is not described in detail.

2 How to get a connection string

The method of obtaining a connection string is as follows, which is written in a base class form (component).

See BaseComponent.cs (definition) and DatabaseForm.cs (reference)

Public String getConnectString ()

{

Return this.sqlConnection1.connectionstring;

}

转载请注明原文地址:https://www.9cbs.com/read-25964.html

New Post(0)