MySQL client program 4-Get connection parameters at run time

Source: Internet
Author: User
Tags array functions header connect mysql mysql client variable access


6.5 client program 4-Get connection parameters at run time
Now that we have the easy to modify connection code to prevent errors, we need to learn how to do something more dexterous than using NULL connection parameters, such as allowing the user to specify some values at run time. Client program 3 due to fixed connection parameters, to change any of those values, you must edit the source file and recompile. This is very inconvenient, especially if you want to make the program available to other people. A common way to specify connection parameters at run time is to use command-line options. The program in the MySQL distribution contract accepts two forms of connection parameters, as shown in table 6-1.

Consistent with the standard MySQL client program, the client program accepts the same format. This is easy because the client library includes functions that implement option analysis.
In addition, the client program has the ability to extract information from the option file. This allows the connection parameters to be placed in the-/.my. C N F (that is, the. my.cnf file in the home directory) so that you do not have to specify them on the command line. The client library makes it easy to check the MySQL option files and extract any associated values from them. By adding just a few lines of code to your program, you can make the option file recognize it and manipulate it by writing your own code without having to reinvent the framework. The syntax for the option file is described in Appendix E, "MySQL program reference."
6.5.1 access to option file contents
Use the Load_default () function to read the option file for the connection parameter value, Load_default () to find the option file, analyze the contents of any optional group of interest, and rewrite the parameter vector (a rgv[] array of the program), So that the information from those groups is placed at the beginning of the argv[in the form of command line options. This means that the options that appear are specified on the command line. Therefore, when you parse the command options, you get the connection parameters that are part of the analysis loop as a general option. option is added to the beginning of argv[] rather than to the end, so if the connection parameters are really specified on the command line, they will appear later (and thus ignored) any options that are added by Load_defaults (). The small program Show _ argv shows how to use the load _ defaults (), and give examples of how the parameter vectors make such modifications:

The code for the processing options file includes:
Groups[] is an array of strings representing the groups of options that interest you. For the client program, always specify at least the "client" group. The last element of the array must be null.
My_init () is an initialization routine required by Load_defaults () to perform some setup operations.
Load_defaults () has four parameters: the prefix of the option file (which should always be "my"), lists the array of optional groups of interest, the number of program parameters, and the address of the vector. Does not pass the number and vector values, but rather the address, because Load_defaults () needs to change their values. The special note is that although a rgv is a pointer, it still wants to pass & argv, which is the address of the pointer.
Show _ argv print Parameters two times, the first time they are specified on the command line, and the second time when the load _ defaults () modifies them. In order to see the effect of load_defaults (), you should be sure that there is one in the home directory that has the specified settings in the [client] group. MY.CNF files. Assume. MY.CNF files are as follows:

It is possible to see some of the options in the output resulting from the S H o W _ a rgv in the command line or in the ~/.my.cnf file. If so, they may be specified in the System-wide options file. Before reading. My.cnf in the home directory, Load_defaults () is actually looking for/E t c/my.cnf and my.cnf files in the MySQL data directory (in Windows, Load_defaults () Looking in the Windows system directory File C:My. c N F, c: \ mysql\ d a t a \ my.cnf and My.ini).
A client program that uses Load_defaults () is almost always specifying "C L I e n T" in the list of option groups (to get any common client settings from the option file), but you can also request a specific value for your own program. The following code can be used:

Modified to:

Then add the [show _ argv] group to the ~/. MY.CNF file:

With these changes, calling show _ argv a different result, as follows:

The order in which the option values appear in the parameter array depends on the order in which they are listed in the options file, not the order in which the option group is listed in the group[] array. This means that a program-specific group may be specified after the [client] group of the option file. That is, if an option is specified in two groups, the program's proprietary values will have higher precedence. As you can see in this example, the host option is specified in group [client] and [show _ argv], but because the group [show _ argv] appears at the end of the option file, the host value appears in the parameter vector and gets precedence.
Load_defaults () is not extracted from the environment settings, if you want to use the value of environment variables, such as MySQL _ TCP _ port or MySQL _ UNIX _ port, you must use GETENV () to manage. I don't want to add this management capability to the client, but here's an example of how to check several standard MySQL-related environment variable values:

In a standard MySQL client, the precedence of the value of an environment variable is lower than the priority assigned to the value in the option file or the command line. If you check the value of an environment variable and you want to keep it consistent with the contract, check the environment before calling Load_default () or processing command-line options (not after).
6.5.2 Parsing command line arguments
Now we can put all the connection parameters into the parameter vector, but we need a method to analyze the vector. The Getopt_long () function is designed for this purpose. Getopt_long () is located inside the MySQL client library, so you can access it whenever you connect to the library. To include the Getopt.h header file in the source file, you can copy the header file from the Include directory of the MySQL source distribution package to the directory where the client program is being developed.
Load_defaults () and security
Because some programs, such as P s, can display a list of parameters for any procedure, load_defaults () places the text of the password in the argument list, so you may be amazed at what it does with the prying meaning. This is fine because PS displays the original a rgv[] content, and any password parameters created by Load_defaults point to the area of its own allocation, which is not part of the original area, so PS cannot see it. On the other hand, the password specified on the command line will appear in PS unless deliberately cleared. 6. 5. Section 2, "Analyzing Command-Line arguments," describes how to do this. The following program Show_param uses Load_defaults () to read the option file and then calls Getopt_long () to divide
An analysis of the parameter vectors. Show_param illustrates what happens at each stage of processing by performing the following operational parameters:
1 Set the default value of the host name, user name, and password.
2 print the original connection parameters and parameter vector values.
3) Call Load_defaults () to rewrite the parameter vector, reflect the contents of the option file, and then print the result vector.
4 Call Getopt_long () to process the parameter vector, and then print the result parameter value and the remainder of the parameter vector.
Show_param allows you to experiment with a variety of specified connection parameters, whether in an option file or on the command line, and to view the results by displaying what values are used to connect. When we actually connect the parameter handling code with the Join function Do_connect (), Show_param is useful for predicting what will happen to the next client program.
Here's the code for SHOW_PARAM.C:




To handle the parameter vector, show _ argv () uses Getopt_long (), which is called in the loop:

The first two parameters of Getopt_long () are the count and vector parameters of the program, and the third parameter lists the option characters to identify. These are the short name forms for program options. An option character can have a colon, a double colon, or no colon, indicating that the option value must follow the options, follow the options, or not follow the options. The fourth parameter, long_options, is a pointer to an array of optional structures, with each optional structure specifying information for the options that the program needs to support. Its target is similar to the optional string for the third parameter. Each long_options[] structure has four elements, which are described as follows:
The long name of the option.
The option value. This value can be required _ argument, optional _ argument, or no _ argument, indicating whether the option values must follow the options, follow the options, or not follow the options (they are the colon in the third argument option string, Double colon or no colon is the same effect.
Tag parameters. It can be used to store variable pointers. If this option is found, Getopt_long () stores the value specified by the fourth argument in the variable. If the tag is Null,getopt_long (), point the OPTARG variable to any value of the next option and return the short name of the option. long_options[] array specifies null for all options. That is, if you encounter getopt _ Long (), return each argument so that we can handle it in a switch statement.
The short (single character) name of the option. The short name specified in the long_options[] array must match the letter used by the option string passed to Getopt_long () as the third argument, otherwise the program will not handle command-line arguments correctly. The long_options[] array must be terminated by a struct that has all elements set to 0. The fifth parameter of Getopt_long () is a pointer to an int variable. Getopt_long () stores the long_options[] structure index in accordance with the last encountered option (Show_param do nothing with this value).
Note that the password option (specified as--password or-p) can get an option value, that is, if you can specify--password or--password = Your_pass using the long option form, if you use the short option form, specify either-P or-p Your _ Pass. The optional _ argument in the double colon and long_options[] array after "P" in an optional string represents an optional attribute of the password value. In particular, the MySQL client allows the password value to be omitted from the command line, and then prompts for input. This avoids giving a password at the command line, which prevents others from seeing the password by stealing. When you write the next client program (client program 4), the password check performance is added. Here is the Show_param invocation example and the result output (assuming ~/.my.cnf has the same content as the show _ argv example):

The output indicates that the host name is obtained from the command line (ignoring this value in the option file), and the user name and password are obtained from the option file. Getopt_long () correctly analyzes whether the option is specified in the Short option form (-H host_name) or in the Long option form (--user = Paul,--password = secret).
Now let's get rid of this part of how the option processing routine works, and the rest as the basis for a client that connects to the server based on any option provided by the option file or command line. The code for the source file client4.c is as follows:




Compared to the client program 1, client program 2, and client program 3 previously developed, client program 4 has something that was not previously:
Allows you to specify the database name on the command line, which is immediately after the option parsed by Getopt_long (). This is consistent with the behavior of the standard client in the MySQL distribution.
After the password value is backed up, any password values in the parameter vector are deleted. This minimizes the time window, in which the password specified by the command line is visible to PS or other System state programs (the window is minimized but not deleted.) The password specified on the command line is still not secure.
If a password option is given without a value, the client program prompts the user to enter the password with Get_tty_password (). In the client library, this is a utility that prompts for a password and does not respond on the monitor (the client library is full of such compelling things.) This helps to read from the source files of the MySQL client program because the associated routines and methods used are found. You might ask, "Why not just call Getpass ()?" "The answer is that not all systems have this function, such as Windows." Get_tty_password () can be ported between systems because it is configured to accommodate a variety of different systems.
Client program 4 responds with the specified options. Suppose you don't have an option file that complicates events. If no parameters call client program 4, connect to localhost and pass the UNIX registration name and no password to the server. Conversely, if client program 4 is invoked as described, prompts for a password (no password value that begins with-P), connects to the some _ host, and passes the user name Some_user and the password you typed to the server:

Client program 4 also passes the database name some_db to do _ Connect () and becomes the current database. If there is no option file, the content is processed and the parameter connection is changed.
Early on, we were interested in encapsulating code and creating wrapper functions to disconnect from the server and disconnect from the server. It is also reasonable to ask whether the Analysis Options section is placed in the wrapper function. I think it's possible, but I don't want to do it. Option parsing code and connection code are not consistent between programs: programs often support other than standard options
Other options, different programs are likely to support different settings for other options. This makes it difficult to write a function that standardizes the option-handling cycle. Moreover, unlike connection creation, the program can expect to do multiple times (and thus a good encapsulation candidate) during its execution, and option analysis is performed only once at the beginning of the program.
So far, we've done what every MySQL client program has to do: Connect to the server with the appropriate parameters. Of course you should know how to connect, now you know what to do, and the details of the processing are implemented by the client program framework (CLIENT4.C), so you don't have to think about it. That means you can focus on what's really interesting-accessing the contents of the database. All the true features in the application will occur between the Do_connect () call and the Do_disconnect () call, but what we now have is to build the basic framework that can be used for many different client programs. Write a new program to do the following:
1) make a client4.c backup.
2 If you accept other options rather than the standard options supported by CLIENT4.C, modify the processing option loop.
3 Add your own application code between the connection and the disconnect call.
It's done.
The purpose of constructing the client program framework is to easily build and disconnect so that you can focus on what you really want to do.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.