1.安装mysql客户端
用命令:
yum install -y mysql-server mysql mysql-devel
此命令包含了安装客户端和服务器
2.访问myslq
在命令行输入:
mysql -h192.168.0.36 -uroot -p123456
出现:
Welcome to the MySQL monitor. Commands end with ; or g.
Your MySQL connection id is 45099
Server version: 5.5.5-10.0.12-MariaDB MariaDB Server
Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners
代表Mysql客户端安装成功!
在安装mysql的机器上运行:
1、d:mysqlin>mysql -h localhost -u root //这样应该可以进入MySQL服务器
2、mysql>GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION //赋予任何主机访问数据的权限
3、mysql>FLUSH PRIVILEGES //修改生效
4、mysql>EXIT //退出MySQL服务器
这样就可以在其它任何的主机上以root身份登录啦!
3.代码访问
#include <iostream> #include <mysql/mysql.h> #include <string> using namespace std; int main() { MYSQL mysql; mysql_init(&mysql); mysql_real_connect(&mysql, "192.168.0.36", "root", "123456", "uc", 3306, NULL, 0); string sql = "insert into sysuser (orgid,useraccount) values (1, 'java1');"; mysql_query(&mysql, sql.c_str()); mysql_close(&mysql); return 0; }
编译:
g++ -o test main.cpp -lmysqlclient -I/usr/include/mysql/ -L/usr/lib64/mysql
注意:-L的路径在lib64下面
4.查询实例代码
#include <iostream> #include <string> #include <mysql/mysql.h> using namespace std; int main() { MYSQL mysql; MYSQL_RES *result = NULL; MYSQL_FIELD *field = NULL; mysql_init(&mysql); mysql_real_connect(&mysql, "192.168.0.36", "root", "123456","uc", 3306,NULL, 0); // mysql_real_connect(&mysql, "localhost", "root", "root", "test", 3306, NULL, 0); string sql = "select id,useraccount from sysuser;"; mysql_query(&mysql, sql.c_str()); result = mysql_store_result(&mysql); int rowcount = mysql_num_rows(result); cout <<"rowcount:"<< rowcount << endl; int fieldcount = mysql_num_fields(result); cout <<"fieldcount:"<< fieldcount << endl; for(int i = 0; i < fieldcount; i++) { field = mysql_fetch_field_direct(result,i); cout << "field name:"<<field->name << " "; } cout << endl; MYSQL_ROW row = NULL; row = mysql_fetch_row(result); while(NULL != row) { for(int i=0;i<fieldcount; i++) { cout << "row"<<i<<":"<<row[i] << " "; } cout << endl; row = mysql_fetch_row(result); } mysql_close(&mysql); return 0; }