C++ mysql

txt 2020-05-02

MYSQL *my;
//①初始化MYSQL
my=mysql_init(NULL);
char ip[]="127.0.0.1";
char user[]="root";
char pass[]="123";
char database[]="testx";
int port = 3306;
//②建立连接
if(mysql_real_connect(my,ip,user,pass,database,port,NULL,0)) {
    cout<<"connect success"<<endl;
}
else {
    cout<<"connect failed"<<endl;
    return;
}
//③准备查询结果需要的结构
MYSQL_RES* result;  //返回查询结果
MYSQL_ROW row;      //表示一行数据
int num;
//③执行sql语句
if((mysql_query(my,"select * from person")) == 0) {
    cout<<"query success"<<endl;
}    
//将结果地址存到result
result = mysql_store_result(my);
//有多少列
num = mysql_num_fields(result);
int num2 = mysql_field_count(my);
//本次操作影响了/查询到了多少行数据
int m = mysql_affected_rows(my);    
//打印列/字段名
for(int i=0;i<num2;i++) {
    MYSQL_FIELD *xx;
    xx = mysql_fetch_field(result);  //每执行一次,就指向下一个位置
    cout<<xx->name<<" ";
}
cout<<endl;
//打印所有行数据
while(row=mysql_fetch_row(result)) {
    for(int i=0;i<num;i++) {
        cout<<row[i]<<" ";
    }
    cout<<endl;
}    

//④关闭连接,释放资源
mysql_free_result(result);
mysql_close(my);

https://www.php.cn/mysql-tutorials-64033.html

相关推荐