Connecting to the Mysql database using C language involves two steps:
1. initialize a connection handle Structure
2. actually connect
Use mysql_init to initialize the connection handle
# Include <mysql. h>
MYSQL * mysql_init (MYSQL *);
Generally, if you pass NULL to this routine, it returns a pointer pointing to the new connection handle structure. If you pass an existing structure, it will be reinitialized. This routine returns NULL when an error occurs.
If a structure is allocated and initialized, you still need to use mysql_real_connect to provide parameters for a connection:
MYSQL * mysql_real_connect (MYSQL * connection,
Const char * server_host,
Const char * SQL _user_name,
Const char * SQL _password,
Const char * db_name,
Unsigned int port_number,
Const char * unix_socket_name,
Unsigned int flags ,);
Connection: point to the structure initialized by mysql_init.
Server_host: the host name or IP address. If you only connect to the local machine, you can specify localhost to optimize the connection type.
SQL _user_name: Database Login Name
SQL _password: Database Password
Db_name: Database Name
Port_number: Port Number (the default Mysql setting is not changed, and 0 indicates the default value)
Unix_socket_name: NULL indicates the default value.
Flags: it is used to perform OR operations on some defined bit modes to change some features of the Protocol.
Void mysql_close (MYSQL * connection );
Close the connection. If the connection is established by mysql_init, the MySQL structure will be released. The pointer will be invalid and cannot be used again. It is a waste of resources to keep an unnecessary connection, but re-opening the connection also brings additional overhead, so you must weigh when to use these options.
Mysql_options (can only be called between mysql_init and mysql_real_connect)
Int mysql_options (MYSQL * connection, enum option_to_set, const char * argument );
Because only one option can be set for mysql_options at a time, each option must be called once. You can call it multiple times as long as it appears between mysql_init and mysql_real_connect.
List the three most common options:
Enum Option |
Actual parameter type |
Description |
MySQL_OPT_CONNECT_TIMEOUT |
Const unsigned int * |
Waiting seconds before connection timeout |
MySQL_OPT_COMPRESS |
Use NULL |
Use compression mechanism in network connection |
MySQL_INIT_COMMAND |
Const char * |
Command sent after each connection is established |
0 is returned for a successful call.
Connect the database named test on the local server with the username root and password yao
Connect. c
#include <stdlib.h>#include <stdio.h>#include "mysql.h" int main(int argc,char **argv){ MYSQL * conn_ptr; conn_ptr = mysql_init(NULL); if(!conn_ptr) { perror("mysql_init failed\n"); exit(1); } conn_ptr = mysql_real_connect(conn_ptr,"localhost","root","yao","test",0,NULL); if(conn_ptr){ printf("connection success\n");} else{ printf("connection failed\n");} mysql_close(conn_ptr); return 0;}
To compile this program, you must add both the include path and the library file path, and specify the library module mysqlclient linked to it.
Gcc-I/usr/include/mysql connect. c-L/usr/lib/mysql-lmysqlclient-o connect
Possible errors:
In Centos 6.4 64-bit system, mysqlclient cannot be found when Mysql is accessed using C language
Solution:
Change-L/usr/lib/mysql to-L/usr/lib64/mysql
Error Handling
MySQL uses a series of return codes reported by the connection handle structure.
Unsigned int mysql_errno (MYSQL * connection );
Char * mysql_error (MYSQL * connection );
Call mysql_errno and pass the connection structure to obtain the error code. Generally, the error code is not 0. If no error code is set, it returns 0. Because the error code is updated every time you call the database, you can only get the error code of the last command. The above two error checking functions are exceptions and will not cause updates of error codes.
The returned values of mysql_errno are actually error codes, which are defined in the header file errmsg. h or mysqld_error.h. Both files can be found in the include directory of MySQL. The former reports client errors, while the latter focuses on server errors.
If you like text information errors, call mysql_error to provide meaningful text information, which is written into some internal static memory space.
Use a non-dynamically allocated Connection Structure
#include <stdlib.h>#include <stdio.h>#include "mysql.h" int main(int argc,char **argv){ MYSQL mysql_conn; mysql_init(&mysql_conn); if(mysql_real_connect(&mysql_conn,"localhost","root","dfdsfjfd","test",0,NULL)){ printf("connection success\n"); mysql_close(&mysql_conn);} else{ perror("connection failed\n"); if(mysql_errno(&mysql_conn)) { fprintf(stderr,"connection error %d:%s\n",mysql_errno(&mysql_conn),mysql_error(&mysql_conn)); }} return 0;}
Note: The dynamically allocated connection structure is used here, and error messages are not generated.
Execute SQL statements
The SQL statement execution function is
Int mysql_query (MYSQL * connection, const char * query );
This function accepts valid SQL statements in the form of connection structure pointers and text strings (no end semicolon ). If the query succeeds, 0 is returned. For queries containing binary data, you can use the second function mysql_real_query.
1. SQL statement that does not return data
SQL statement that does not return any data: update delete insert
Another important function is introduced here to check the number of rows affected by the first query.
My_ulonglong mysql_affected_rows (MYSQL * connection );
The Return Value Type of this function is very uncommon. It uses the unsigned type. When you use printf, we recommend that you convert it to an unsigned long integer in % lu format. This function returns the number of rows affected by the previously executed update, insert, or delete queries. If you have used other SQL databases, MySQL returns the number of rows modified by an update operation, but many other databases regard it as updated only because the record matches the where clause.
Insert a data entry
#include <stdlib.h>#include <stdio.h>#include "mysql.h" int main(int argc,char **argv){ MYSQL mysql_conn; int res; mysql_init(&mysql_conn); if(mysql_real_connect(&mysql_conn,"localhost","root","yao","test",0,NULL)){ printf("connection success\n"); res = mysql_query(&mysql_conn,"insert into child(childid,age,name) values (1,12,'bing')"); if(!res) { printf("inserted %lu rows\n",(unsigned long)mysql_affected_rows(&mysql_conn)); } else{ fprintf(stderr,"insert error %d:%s",mysql_errno(&mysql_conn),mysql_error(&mysql_conn)); } mysql_close(&mysql_conn);} else{ fprintf(stderr,"connection failed\n"); if(mysql_errno(&mysql_conn)) { fprintf(stderr,"Connection error %d:%s\n",mysql_errno(&mysql_conn),mysql_error(&mysql_conn)); }} return 0;}
Come here today, and continue to add...
This article from the "technology lies in persistence" blog, please be sure to keep this source http://minilinux.blog.51cto.com/4499123/1300703