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;
}