MySQL database technology (32) [group chart] 6.4 client program 3-generate connection code module
For our third client program, client program 3, the connection and disconnection code will be more modularized by encapsulating it into functions do_connect () and do_disconnect, this can be easily used by multiple client programs. This provides an option to precisely embed the connection code into the main () function. In any case, it is a good idea to apply any old code in the application process. Place it in a function that can be accessed through multiple programs, instead of writing it in each program. If you modify an error in the function or make some improvements to the function, you can change it only once, all programs that can use this function can be modified or used by re-compilation. Similarly, write some client programs so that they can be connected and disconnected several times during execution. If you place the installation and uninstallation methods in the connection and disconnection functions, it is easier to write such a client. The encapsulation policy is as follows:
1) separate the public code into a wrapper function of an independent source file (common. c.
2) provide a header file, common. h, including the prototype of this common routine.
3) include common. h in the client source file using the common routine.
4) compile the public source file into the target file.
5) connect the public target file to your client program.
With these policies, Let's construct do_connect () and do _ disconnect ().
Do_connect () replaces the call to mysql_init () and mysql_real_connect (), and replaces the error print code. You can call it like mysql_real_connect () without passing any connection handler. Do_connect () allocates and initializes the handler, and then returns a pointer to it after the connection. If do _ connect () fails, n u l is returned after an error message is printed (that is, do_connect () is called () and any program that obtains the return value n u l can simply exit, without worrying about printing the message itself ). Do _ disconnect () generates a pointer to the connection handler and calls mysql_close (). Here is the code for common. c: