安装mysql
1、brew install mysql
2、mysql_secure_installation 修改密码
3、mysql -u root -p 登陆
编辑node-gyp binding.gyp
1、brew --prefix mysql 获取安装目录
2、include_dirs 添加
"/usr/local/Cellar/mysql/8.0.17/include"
" /usr/local/Cellar/mysql/8.0.17/include/mysql"
3、libraries 添加 "/usr/local/Cellar/mysql/8.0.17/lib/libmysqlclient.a"
4、node-gyp configure
5、node-gyp build
6、node-gyp configure -- -f xcode
代码
1、引入头文件
#include <mysql/mysql.h>
2、初始化链接
MYSQL*conn;
3、node addon init创建mysql connection
std::stringserver ="localhost";
std::stringuser ="root";
std::stringpassword ="****";
std::stringdatebase ="testdb";
conn=mysql_init(NULL);
if(!mysql_real_connect(conn, server.c_str(), user.c_str(), password.c_str(), datebase.c_str(),0,NULL,0)) {
std::cout<<"connect to database error"<
exit(1);
}
4、node::AtExit关闭mysql 链接
node::AtExit(atExitCallback);
staticvoidatExitCallback(void* arg) {
mysql_close(conn);
std::cout<<"close conn"<
}
5、执行查询
void RunCallback(const Nan::FunctionCallbackInfo<Value> &info) {
MYSQL_RES* res;
MYSQL_ROW row;
if (mysql_query(conn, "SELECT * FROM Cars")) {
std::cout<<"send SQL query"<< std:endl;
}
res = mysql_use_result(conn);
while((row =mysql_fetch_row(res)) !=NULL) {
std::cout<< row[0] <<','<< row[1] <<','<< row[2] <
}
mysql_free_result(res);
}