MySQL Connector 是MySQL数据库客户端编程的接口, 它提供了经过网络访问数据库的接口, 这些功能在动态连接库(.dll, .so)或者静态对象库(.lib, .a)中实现.mysql
使用时必须注意这些库是32位仍是64位的.sql
下面是一个例子:数据库
#include <stdio.h>
#include <stdlib.h> #include <C:\Program Files\MySQL\MySQL Connector C 6.1\include\mysql.h> // 使用静态对象库 //#pragma comment(lib, "C:\\Program Files\\MySQL\\MySQL Connector C 6.1\\lib\\vs12\\mysqlclient.lib") // 使用动态连接库 // 确保 libmysql.dll 在系统路径中能够搜到 #pragma comment(lib, "C:\\Program Files\\MySQL\\MySQL Connector C 6.1\\lib\\libmysql.lib") void simpleUsega() { MYSQL *conn; conn = mysql_init(NULL); if (conn == NULL) { printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn)); exit(1); } if (mysql_real_connect(conn, "localhost", "user_name", "user_password", NULL, 0, NULL, 0) == NULL) { printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn)); exit(1); } if (mysql_query(conn, "create database frist_db")) { printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn)); exit(1); } mysql_close(conn); } int main() { MYSQL *mysql = NULL; char pwd[1024]; char usr[1024]; printf("Target platform word length : %d \n", sizeof(void*) ); printf("Connector version: %s \n", mysql_get_client_info()); //simpleUsage(); //return 0; printf("Initializing MySQL Connector... \n");
mysql_library_init(0, NULL, NULL); // 在其余work线程产生以前初始化mysql c库, 不要让mysql_init来调用, 不然可能致使线程安全问题 if (!(mysql = mysql_init(NULL))) { printf("Field. \n"); goto end; } printf("OK, Conecting... \n");
// 配置用户和密码 if (0) { printf("Please keyin user_name and password \n" "name: "); scanf_s("%s", usr, 1024); printf("pwd : "); scanf_s("%s", pwd, 1024); } else { sprintf_s(usr, 1024, "default_user_name"); sprintf_s(pwd, 1024, "default_user_password"); }
// 链接 localhost 上的服务器 if (!mysql_real_connect(mysql, "localhost", usr, pwd, (const char*) 0, 3306, NULL, 0)) { printf("Filed, Error %u, %s \n", mysql_errno(mysql), mysql_error(mysql) ); goto end; } printf("Login succeed. \n"); // 销毁密码 sprintf_s(pwd, 1024, "00000000000000");
// 查询数据库服务器时间 mysql_query(mysql, "SELECT NOW();"); if (!mysql_errno(mysql)) { MYSQL_RES *result; MYSQL_ROW row; int num_fields; int i; result = mysql_store_result(mysql); num_fields = mysql_num_fields(result); while ((row = mysql_fetch_row(result))) { for(i = 0; i < num_fields; i++) { printf("%s ", row[i] ? row[i] : "NULL"); } printf("\n"); } mysql_free_result(result); } end: system("pause"); mysql_close(mysql); mysql_library_end(); return 0; }