1. Database Connection
1. Connect to the database where the database needs to be connected. For example:
1 public class SQLHleper
2 {
3 public int ExecuteNonQuery(string sql)
4 {
5 connstr="server=.;database=newssystem;uid=sa;pwd=123";
6 SqlConnection conn = new SqlConnection(strconn);
7 conn.Start();
8 ..........
9 conn.Close();
10 }
11 }
This method is obviously used by beginners. I will not talk about it here...
1 public class SQLHleper
2 {
3 connstr="server=.;database=newssystem;uid=sa;pwd=123";
4 SqlConnection conn = new SqlConnection(strconn);
5
6 public int ExecuteNonQuery(string sql)
7 {
8 conn.Start();
9 ..........
10 conn.Close();
11 }
12
13 public int Execute(string sql)
14 {
15 conn.Start();
16 ..........
17 conn.Close();
18 }
19 }
The advantage of this method is that you only need to establish a connection at the beginning. In the future, no matter how many places you have, you can directly use the database connection.
3. Use the configuration file to establish a database connection.
The procedure is as follows: (1) Open the web. config, change <connectionstrings/> to <connectionstrings> <Add name = "connstr" connectionstring = "Server = .; database = newssystem; uid = sa; Pwd = 123 "/> </connectionstrings>
(2) introduce the namespace using system. configuration where you need to connect to the database;
(3) Right-click the "Reference" option in the project, click Add reference, select Add system. Configuration component in · net, and click OK.
(4) add string strconn = configurationmanager. connectionstrings ["connstr"]. connectionstring; to establish a database connection.
This method is good because once the password of your database is modified, you do not have to open your project to modify your password, but simply use NotePad to open the web. you can change the password in the config file.
Ii. Exception Handling
1. The most common method is:
Try ()
{}
Catch (exception ex)
{Throw ex ;}
Finally
{}
2. Another method is the using statement. We all know that using can introduce namespaces, but it can also handle exceptions. It defines a range to process objects at the end of the range.
When a class instance is used in a code segment, you want to automatically call the dispose of the class instance as long as you leave the code segment for whatever reason. To achieve this goal, it is also possible to catch exceptions using try... catch, but it is also convenient to use using.
For example:
Using (class1 cls1 = new class1 (), cls2 = new class1 ())
{
// The code using cls1, cls2
} // Call the dispose on cls1 and cls2
Here, the dispose condition that triggers cls1 and cls2 is to reach the end of the using statement or throw an exception in the middle and control to exit the statement block.
2. if there are many methods in a class, and each method needs to connect to the database, it is very resource-consuming. This is where we need to establish a database connection.