Today, the user proposed to select the test database and official database when logging on to the system.
The database connection string is stored in dbconn. in the XML file, the original test zone and the formal zone are independent (two independent systems), so when operating on the database, select your xml file and read the connection string.
If you want to put them together, you should first choose whether to test the database or the official database during login. mark the selected XML file.
Database Connection class:
Class connstring
{
Private int selectindex;
Public int selectindex
{
Get
{
Return selectindex;
}
Set
{
Selectindex = value;
}
}
Public void connstring ()
{
If (selectindex = 0)
{
// Read the connection string connstring of the Test Database
}
Else
{
// Read the official database connection string connstring
}
}
// Connect to and operate the database using the string connstring.
}
At login:
Connstring conn = new connstring ()
If (Select Test Database)
{Conn. selectindex = 0 ;}
Else
{Conn. selectindex = 1 ;}
After doing so, I thought there was no problem. After the test, I found that no matter which database I chose, the data displayed by the system will always be the data in the test zone !!
After tracking and debugging, we found that:
After the selection, for example, select the formal zone, the selectindex field in the class is displayed as 1 as expected; however, when I want to call other methods in the class to operate the database (of course, I want to perform the new operation on the class), The selectindex field is initialized to 0 .......
You have to make sure that the selectindex field cannot be changed after the value is initially assigned until the system exits.
So I thought of using the static keyword. static fields belong to Classes and do not belong to objects, so they cannot be instantiated. Once a value is assigned, the value is stored in the memory for future calls and will not be released until the system exits.
Struct dbtype
{
Public static int selectindex;
}
Class connstring
{
Public void connstring ()
{
If (dbtype. selectindex = 0)
{
// Read the connection string connstring of the Test Database
}
Else
{
// Read the official database connection string connstring
}
}
// Connect to and operate the database using the string connstring.
}
At login:
If (Select Test Database)
{Dbtype. selectindex = 0 ;}
Else
{Dbtype. selectindex = 1 ;}
The problem is solved!