今天,碰巧有人问,说写的代码server_init,老是失败,我不信,试了一番,大费周折,总算成功。
有兴趣的,不妨自己动手一试,蛮有意思的。
我机器上原本有一个解压缩版的MySQL5.0.9,位于D:/program/mysql-5.0.9-beta-win32,默认存储引擎是InnoDB
1. 为便于测试,首先建立一个测试表,并插入几条记录,引擎定为MyISAM
create table t2(id int primary key, col2 varchar(32)) engine=MyISAM;
2. 创建Embed Server的配置文件,
D:/program/mysql-5.0.9-beta-win32/Embedded/my.ini,值得一提的是,差点把我害惨了,就是Server那一项的名字必须与你的Server程序的名字保持一致。这里,EmbedMySQLServer就是我后边的exe程序的名,否则server永远也启不来。
内容如下:
[EmbedMySQLServer]
basedir = D:/program/mysql-5.0.9-beta-win32
datadir = D:/program/mysql-5.0.9-beta-win32/data
language = D:/program/mysql-5.0.9-beta-win32/share/english
skip-innodb
port=3306
[libmysqld_client]
language = D:/program/mysql-5.0.9-beta-win32/share/english
port=3306
3. 开始写自己的代码了
create EmbedMySQLServer.exe, source code like:
// #define _WIN32_WINNT 0x0400
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "mysql.h"
MYSQL *mysql;
MYSQL_RES *results;
MYSQL_ROW record;
#pragma comment(lib, "D://program//mysql-5.0.9-beta-win32//Embedded//DLL//debug//libmysqld.lib")
static char *server_options[] = { "mysql_test", "--defaults-file=D:/program/mysql-5.0.9-beta-win32/Embedded/my.ini" };
int num_elements = sizeof(server_options)/ sizeof(char *);
static char *server_groups[] = { "EmbedMySQLServer", "libmysqld_client" };
int main(void)
{
int ret = mysql_server_init(num_elements, server_options, server_groups);
printf("return %ld/n", ret);
mysql = mysql_init(NULL);
mysql_options(mysql, MYSQL_READ_DEFAULT_GROUP, "libmysqld_client");
mysql_options(mysql, MYSQL_OPT_USE_EMBEDDED_CONNECTION, NULL);
MYSQL* t = mysql_real_connect(mysql, NULL,"test","test", "test", 0,NULL,0);
mysql_query(mysql, "SELECT id, col2 FROM t2");
results = mysql_store_result(mysql);
while((record = mysql_fetch_row(results))) {
printf("%s - %s /n", record[0], record[1]);
}
mysql_free_result(results);
mysql_close(mysql);
mysql_server_end();
return 0;
}
4. 最终运行结果:
return 0
1 - test
2 - test
3 - test
4 - test
5 - fdas
Press any key to continue
像这类东东,MySQL Online Doc都没好好说,它都推荐买它的商业license,看来自己多动动手,也蛮有意思的。