Mysql VS2015調用

  • VS2015 調用mysql的demo筆記
  • 整理了下網上的內容,這裏記一下
    1.創建任意終端程序;
    2.指定包含頭文件路徑:
    Project->properties->C/C++->Additional Include Directories->(這裏指定mysql各種頭文件的目錄,我的是mysql文件夾裏的include)
    3.指定lib路徑:
    Project->properties->Linker->General->Additional Library Directories->(這裏是libmysql.lib所在路徑,我的是在lib裏)
    4.添加lib:
    Project->properties->Linker->Input->Additional Dependencies->增加libmysql.lib
    5.修改配置:
    Build->Configuration Manager->Active solution platform->x64
    (爲了避免模塊計算機類型x64與目標計算機類型x86衝突

    6.將libmysql.dll放到新建的終端程序源代碼下;

以下爲測試代碼:

// ConsoleApplication1_mysql_01.cpp : Defines the entry point for the console application.
//

#pragma comment(lib,"libmysql.lib")
#pragma comment(lib, "ws2_32.lib")
#include "stdafx.h"
#include <winsock.h>
#include "mysql.h"
#include <iostream>
#include <stdlib.h>

#include <stdio.h>  
#include <mysql.h>  

void sqlselect(MYSQL *mysql, char *command)
{

    int flag = mysql_real_query(mysql, command, strlen(command));

    if (flag)
    {
        printf("Select error:%d, %s\n", mysql_errno(mysql), mysql_error(mysql));
        return;
    }

    MYSQL_RES *res = mysql_store_result(mysql); //讀取將查詢結果   
    MYSQL_FIELD *field = mysql_fetch_fields(res); //獲取所有列名
    int field_count = mysql_field_count(mysql); //獲取列數

                                                //輸出所有列名
    for (int i = 0; i < field_count; i++)
    {
        printf("%s\t", field[i].name);
    }

    printf("\n");

    //遍歷輸出每一行數據  
    MYSQL_ROW row;
    while (row = mysql_fetch_row(res))
    {
        for (int i = 0; i < field_count; i++)
        {
            printf("%s\t", row[i]);
        }
        printf("\n");
    }
}

int main()
{
    //初始化MySQL連接句柄
    MYSQL *mysql = NULL;
    mysql = mysql_init((MYSQL *)0);

    mysql_real_connect
    (
        mysql,
        "localhost", //數據庫地址
        "root", //數據庫用戶名
        "123456", //數據庫密碼
        "demo", //數據庫名稱
        0, //數據庫端口,0表示默認端口(即3306)
        NULL, //如果unix_socket不是NULL,字符串指定套接字或應該被使用的命名管道。注意host參數決定連接的類型
        0 //通常是0
    );

    if (!mysql) //連接失敗
    {
        printf("Connection error:%d, %s\n", mysql_errno(mysql), mysql_error(mysql));
    }
    else
    {
        printf("hello world\n");
    }

    char *command = "select * from student"; //查詢指令

    sqlselect(mysql, command); //查詢數據   
    mysql_close(mysql); //關閉連接  

    system("pause");
    return 0;

    return 0;
}

感謝以下作者:
http://blog.csdn.net/daso_csdn/article/details/54646859
https://www.2cto.com/database/201701/587128.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章