tutorial
http://zetcode.com/tutorials/mysqlcapitutorial/
需要安装mysql-connector-c-6.0.2.tar.gz
也就是mysql的c client
yum groupinstall "development tools"
cmake .
make
make install
ldd是查看依赖
ld.so.conf用来在运行时加载的路径
使用ldconfig生效
mysql的root账户,我在连接时通常用的是localhost或127.0.0.1,公司的测试服务器上的mysql也是localhost所以我想访问无法访问,测试暂停.
解决方法如下:
1,修改表,登录mysql数据库,切换到mysql数据库,使用sql语句查看"select host,user from user ;"
mysql -u root -pvmwaremysql>use mysql;
mysql>update user set host = '%' where user ='root';
mysql>select host, user from user;
mysql>flush privileges;
注意:最后一句很重要,目的是使修改生效.如果没有写,则还是不能进行远程连接.
2,授权用户,你想root使用密码从任何主机连接到mysql服务器
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'root' WITH GRANT OPTION;
flush privileges;
如果你想允许用户root从ip为192.168.1.104的主机连接到mysql服务器
GRANT ALL PRIVILEGES ON *.* TO 'myuser'@'192.168.1.104' IDENTIFIED BY 'zhoubt' WITH GRANT OPTION;
flush privileges;
使用mysql_config --libs来生成依赖的项
使用动态编译,但是使用静态的libmysqlclient.a
g++ ./test_mysql.cpp -I/usr/local/mysql/include /usr/local/mysql/lib/libmysqlclient.a -lpthread
使用静态编译
g++ -static ./test_mysql.cpp -I/usr/local/mysql/include /usr/local/mysql/lib/libmysqlclient.a -lpthread
使用动态编译libmysql.so
g++ ./test_mysql.cpp -I/usr/local/mysql/include -L/usr/local/mysql/lib -lmysql -lpthread
source code:
#include <cstdlib>
#include <cstdio>
#include <mysql.h>
int main()
{
printf("===\n");
printf("MySQL client version: %s\n", mysql_get_client_info());
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, "192.168.1.108", "root",
"zhoubt", NULL, 3306, NULL, 0) == NULL) {
printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
exit(1);
}
if (mysql_query(conn, "create database testdb")) {
printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
exit(1);
}
mysql_close(conn);
return 0;
}