c++操作MySQL数据库实例

直接上代码!!!!

#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mysql.h> 
#include <iostream>
using namespace std;

int main()
{
    const char user[] = "root";         //username
    const char pswd[] = "123456";         //password
    const char host[] = "localhost";    //or"127.0.0.1"
    const char database[] = "facedb";        //database
    unsigned int port = 3306;           //server port        
    MYSQL myCont;
    MYSQL_RES *result=NULL;
    MYSQL_ROW row;
    MYSQL_FIELD *fd=NULL;
    char column[32][32];
    int res;
    unsigned long num_col;
    unsigned long num_row;
    int i = 0;

    mysql_init(&myCont);
    char sql[1000];

    if (mysql_real_connect(&myCont, host, user, pswd, database, port, NULL, 0))
    {
        cout << "connect success!!!!!" << endl;
    }
    else
    {
        cout << "connect fail!!!" << endl;
    }
    mysql_query(&myCont,"SET NAMES GBK");//设置编码格式
    strcpy(sql, "select * from result");
    res = mysql_real_query(&myCont, sql, strlen(sql));
    result = mysql_store_result(&myCont);
    if (!result)
    {
        cout << "读取结果失败!!" << endl;
    }
    num_row = (unsigned long)mysql_num_rows(result); //获取行数
    num_col = (unsigned long)mysql_num_fields(result);//获取列数
    cout << "number of row:" << num_row << endl; 
    cout << "number of col:" << num_col << endl; 

    //while (fd= mysql_fetch_field(result)) //获取列名
    //{
    //  printf("%s\t", fd->name);
    //}

    while (fd = mysql_fetch_field(result))//为了便于控制,我们将获取的列名保存到二维数组中。
    {
        strcpy(column[i], fd->name);//拷贝到二维数组中
        printf("%s\t", column[i]);
        i++;
    }
    printf("\n");

    while (row = mysql_fetch_row(result))//获取行数据
    {
        for (i = 0; i < num_col; i++)
        {
            printf("%s\t", row[i]);
        }
        printf("\n");
    }


    mysql_free_result(result);//释放结果资源
    mysql_close(&myCont);//断开连接
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值