This blog is mainly a collection of study notes and some simple tryout examples. For more details, refer to "Beginning Linux Programming", Chapter 8.mysql
Most Commonly Used APIs for Accessing MySQL:sql
MYSQL *mysql_init(MYSQL *); 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); void mysql_close(MYSQL *connection); int mysql_options(MYSQL *connection, enum option_to_set, const char *argument); int mysql_query(MYSQL *connection, const char *query); my_ulonglong mysql_affected_rows(MYSQL *connection); unsigned int mysql_errno(MYSQL *connection); char *mysql_error(MYSQL *connection); MYSQL_RES *mysql_store_result(MYSQL *connection); my_ulonglong mysql_num_rows(MYSQL_RES *result); MYSQL_ROW mysql_fetch_row(MYSQL_RES *result); void mysql_data_seek(MYSQL_RES *result, my_ulonglong offset); MYSQL_ROW_OFFSET mysql_row_tell(MYSQL_RES *result); MYSQL_ROW_OFFSET mysql_row_seek(MYSQL_RES *result, MYSQL_ROW_OFFSET offset); void mysql_free_result(MYSQL_RES *result); unsigned int mysql_field_count(MYSQL *connection); MYSQL_FIELD *mysql_fetch_field(MYSQL_RES *result); char *mysql_get_client_info(void); char *mysql_get_host_info(MYSQL *connection); char *mysql_get_server_info(MYSQL *connection); char *mysql_info(MYSQL *connection); int mysql_select_db(MYSQL *connection, const char *dbname); int mysql_shutdown(MYSQL *connection, enum mysql_enum_shutdown_level);
Example1: how to connect to a mysql serverapp
#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) { fprintf(stderr, "mysql_init failed\n"); exit(EXIT_FAILURE); } conn_ptr = mysql_real_connect(conn_ptr, "localhost", "chenqi", "helloworld", "test", 0, NULL, 0); if (conn_ptr) { printf("Connection Success \n"); } else { printf("Connection failed \n"); } mysql_close(conn_ptr); exit(EXIT_SUCCESS); }
gcc -I/usr/include/mysql connect1.c -L/usr/lib/mysql -lmysqlclient -o connect1less
Example2: how to handle errorssocket
#include <stdlib.h> #include <stdio.h> #include "mysql.h" int main(int argc, char *argv[]) { MYSQL conn; mysql_init(&conn); if (mysql_real_connect(&conn, "localhost", "chenqi", "i do not know", "test", 0, NULL, 0)) { printf("Connection Success \n"); mysql_close(&conn); } else { fprintf(stderr, "Connection Failed \n"); if (mysql_errno(&conn)) { fprintf(stderr, "Connection error %d: %s \n", mysql_errno(&conn), mysql_error(&conn)); } } exit(EXIT_SUCCESS); }
result:ide
chenqi@chenqi-laptop ~/MyPro/Database/access_with_c $ ./connect2
Connection Failed
Connection error 1045: Access denied for user 'chenqi'@'localhost' (using password: YES)fetch
Example3: how to insert and updatespa
/* insert a row into the table children */ ret = mysql_query(&conn, "insert into children(fname, age) values('James', 23)"); if (!ret) { printf("Inserted %lu rows \n", (unsigned long)mysql_affected_rows(&conn)); } else { fprintf(stderr, "Insert error %d: %s \n", mysql_errno(&conn), mysql_error(&conn)); } /* update a row in the table children */ ret = mysql_query(&conn, "update children set age = 24 where fname = 'James'"); if (!ret) { printf("Update %lu rows \n", (unsigned long)mysql_affected_rows(&conn)); } else { fprintf(stderr, "Update error %d: %s \n", mysql_errno(&conn), mysql_error(&conn)); }
result:unix
chenqi@chenqi-laptop ~/MyPro/Database/access_with_c $ ./insert-update
Connection Success
Inserted 1 rows
Update 2 rowscode
Example4: how to retrieve data into C application
Step1: Issue the query (mysql_query)
Step2: Retrieve the data (mysql_store_result, mysql_use_result)
Step3: Process the data (mysql_fetch_row)
Step4: Tidy up if necessary (mysql_free_result)
For a large data set, mysql_use_result should be considered, because it uses less storage.
MySQL, like other SQL databases, gives back two sorts of data:
1. The retrieved information from the table, namely the column data
2. Data about the data, so-called metadata, such as column types and names
#include <stdlib.h> #include <stdio.h> #include "mysql.h" MYSQL my_connection; MYSQL_RES *res_ptr; MYSQL_ROW sqlrow; void display_row() { unsigned int field_count = 0; while(field_count < mysql_field_count(&my_connection)) { if (sqlrow[field_count]) printf("%12s", sqlrow[field_count]); else printf("%12s", "NULL"); field_count++; } printf("\n"); } /* show metadata of each column */ void display_header() { MYSQL_FIELD *field_ptr; printf("Column Details:\n"); while((field_ptr = mysql_fetch_field(res_ptr)) != NULL) { printf("\t Name: %s\n", field_ptr->name); printf("\t Type: "); if (IS_NUM(field_ptr->type)) { printf("Numeric Field\n"); } else { switch(field_ptr->type) { case FIELD_TYPE_VAR_STRING: printf("VARCHAR\n"); break; case FIELD_TYPE_LONG: printf("LONG\n"); break; default: printf("Type is %d, check in mysql_com.h\n", field_ptr->type); } } /* else */ printf("\t Max_width %ld\n", field_ptr->max_length); if (field_ptr->flags & AUTO_INCREMENT_FLAG) { printf("\t Auto increments\n"); } printf("\n"); } /* while */ } int main(int argc, char *argv[]) { int ret; mysql_init(&my_connection); if (mysql_real_connect(&my_connection, "localhost", "chenqi", "helloworld", "test", 0, NULL, 0)) { printf("Conncetion Success\n"); ret = mysql_query(&my_connection, "select * from children"); if (ret) /* error */ { printf("select error: %s\n", mysql_error(&my_connection)); } else /* ok */ { res_ptr = mysql_store_result(&my_connection); /* mysql_use_result for an alternative */ if (res_ptr) { printf("Retrieved %lu rows \n", (unsigned long)mysql_num_rows(res_ptr)); display_header(); while (sqlrow = mysql_fetch_row(res_ptr)) { /// printf("Fetching data ... \n"); display_row(); } if (mysql_errno(&my_connection)) { fprintf(stderr, "Retrieve error: %s\n", mysql_error(&my_connection)); } mysql_free_result(res_ptr); /* res_ptr != NULL */ } } mysql_close(&my_connection); } else { fprintf(stderr, "Connection Failed\n"); if (mysql_errno(&my_connection)) { fprintf(stderr, "Connection error %d: %s\n", mysql_errno(&my_connection), mysql_error(&my_connection)); } exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); }
Result:
chenqi@chenqi-laptop ~/MyPro/Database/access_with_c $ ./select1 Conncetion Success Retrieved 12 rows Column Details: Name: childno Type: Numeric Field Max_width 2 Auto increments Name: fname Type: VARCHAR Max_width 8 Name: age Type: Numeric Field Max_width 2 1 Jenny 21 2 Feby 25 3 Chandler 12 4 Monica 23 5 Rachel 21 6 Ross 2 7 Joy 11 8 Emma 11 9 Gavin 14 10 Andrew 21 12 James 24 13 Tom 13