Original: MySQL programming in C (i)
Beginner MySQL, record the problem that MySQL has encountered when programming in C language.
This is my source program:
1 intMainvoid)2 {3MYSQL *mysql=NULL;4 5 6 if((Mysql=mysql_init (mysql)) = =NULL)7 {8fprintf (stderr,"Cannot initialize MySQL");9 return 1;Ten } One if(Mysql_real_connect (MySQL,"localhost","Kerry","beck123"Null0Null0)==NULL) A { -fprintf (stderr,"%d:%s \ n", Mysql_errno (MySQL), mysql_error (MySQL)); - return 1; the } -printf"succeed!\n"); - return 0; -}
MySQL's C API has several important data types:
Mysql
The structure represents a handle to 1 database connections. It is used by almost all MySQL functions. You should not attempt to copy the MYSQL structure. There is no guarantee that such copies will be useful .
Mysql_res
The structure represents the query results for the returned rows (SELECT, SHOW, DESCRIBE, EXPLAIN). In the remainder of this section, the information returned by the query is referred to as the result set.
Mysql_row
This is the "type-safe" representation of 1 rows of data. It is currently implemented as an array of count byte strings. (If the field value may contain binary data, it cannot be treated as a null -terminated string because such values may contain null bytes). The line is obtained by calling Mysql_fetch_row () .
Mysql_field
The structure contains information about the field, such as the field name, type, and size. Its members are described in detail here. By repeatedly calling Mysql_fetch_field (), you can get the Mysql_field structure for each field. Field values are not part of the structure and are included in the mysql_row structure.
Mysql_field_offset
This is the "type safe" representation of the MySQL field List offset ( used by Mysql_field_seek () ). The offset is the field number within the row, starting at 0 .
Declares "MYSQL *mysql=null;", which must be assigned a value of NULL. If it is defined as "MYSQL *mysql;", and the pointer is not assigned a value, a wild pointer is generated and a "segment error (Core dump)" error occurs when the program runs.
The "Wild pointer" is not a null pointer, it is a pointer to "junk" memory (memory not available). It is generally not wrong to use a null pointer because it is easy to judge with an if statement. But the "wild pointer" is dangerous, if it is not possible to determine whether a pointer is a normal pointer or a "wild pointer". Having a good programming habit is the only way to avoid "wild pointers".
Call the Mysql_init () function, which allocates or initializes a MySQL object that is compatible with Mysql_real_connect () . if MySQL is a NULL pointer, the function allocates, initializes, and returns a new object. Otherwise, the object is initialized and the address of the object is returned. If mysql_init () assigns a new object when mysql_close () is called to close the connection. The object will be disposed.
C Programming for MySQL (i)