【原创】modb 功能设计之“支持部分MySQL客户端协议”-3

 在研究完 MySQL 官方文档上对 Connector/C 的说明后,终于可以 开工实践了,先搞个小 demo 出来运行看看。 

开发环境:Windows XP SP3 v11 + VS2010 + MySQL Connector/C 6.1.2 
测试代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <stdio.h>
#include "mysql.h"
 
int main()
{
    MYSQL mysql;
    MYSQL_RES *res = NULL;
    MYSQL_ROW row;
 
    mysql_init( &mysql );
 
    if ( NULL == ( mysql_real_connect( &mysql,"172.16.81.111","root","root", "", 0, NULL, 0 ) ) )
    {
        fprintf( stderr, "%s: %s\n", "MoDb", mysql_error( &mysql ) );
        exit(1);
    }
 
    if ( mysql_query( &mysql, "show tables" ) ) {
        fprintf( stderr, "Error: %s\n", mysql_error( &mysql ) );
        exit(1);
    }
    res = mysql_use_result( &mysql );
 
    printf("MySQL Tables in mysql database:\n");
    while ( (row = mysql_fetch_row(res)) != NULL )
    {
        fprintf( stderr, "%s \n", row[0] );
    }
 
    mysql_free_result(res);
    mysql_close( &mysql );
 
    getchar();
    return 0;
}

      工程配置好后,运行出现“无法定位程序输入点 InitializeConditionVariable 于动态链接库 KERNEL32.dll 上。”的错误。哈哈,知道为啥不(其实上一篇文章已经说明了这个问题)?我一下就想到了,但还是在度娘那边问查了一下,给出的答案五花八门,相关的不多。其实就是因为 XP 上的 KERNEL32.dll 不支持 InitializeConditionVariable 的缘故。
【原创】modb 功能设计之“支持部分MySQL客户端协议”-3


解决办法 
  • 换操作系统;
  • 降低 MySQL Connector/C 的使用版本。
       其实两种方式都让人觉得不爽,不过好在只是为了在 Windows 平台上能够对编写的 demo 进行迅速调试,所以使用低版本 MySQL Connector/C 获选。 降低版本后,立刻能够正常与 MySQL 进行协议交互了。 
      虽然你可能自以为理解了 MySQL 协议,但是还是不一定能写出正确的协议交互,所以,最简单的办法就是参考一些知名的 MySQL 客户端产品,如 Navicat for MySQL,看看别人是怎么做交互的。

(...抓包分析过程读者自己实践...) 

简单改写后,新的测试代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <stdio.h>
#include "mysql.h"
 
int main()
{
    MYSQL mysql;
    MYSQL_RES *res = NULL;
    MYSQL_ROW row;
 
    mysql_init( &mysql );
 
    if ( NULL == ( mysql_real_connect( &mysql,"172.16.81.111","root","root", "", 0, NULL, 0 ) ) )
    {
        fprintf( stderr, "%s: %s\n", "MoDb", mysql_error( &mysql ) );
        exit(1);
    }
 
    if (  mysql_query( &mysql, "SET NAMES utf8" ) )
    {
        fprintf( stderr, "Error [SET NAMES utf8]: %s\n", mysql_error( &mysql ) );
        exit(1);
    }
 
    if ( mysql_query( &mysql, "show databases" ) ) {
        fprintf( stderr, "Error: %s\n", mysql_error( &mysql ) );
        exit(1);
    }
    res = mysql_use_result( &mysql );
 
    printf("MySQL Tables in mysql database:\n");
    while ( (row = mysql_fetch_row(res)) != NULL )
    {
        fprintf( stderr, "%s \n", row[0] );
    }
 
    mysql_free_result(res);
    mysql_close( &mysql );
 
    getchar();
    return 0;
}

上述代码完成了连接、查询、断开连接的基本操作。 

在上述 demo 成功运行后,又提出了如下问题: 
  • 作为一个主要用于执行 sql 语句的客户端程序,应该采用长连接实现,还是短连接实现?哪种更好?
  • 执行一条 sql 语句在客户端实现中要调用到哪些 API 函数?设置哪些 option ?
  • 应该使用 mysql_use_result 获取结果还是使用 mysql_store_result 获取结果?