windows vscode mingw c++入門(3) 連接mysql

windows vscode mingw c++入門(3) 連接mysql

自備mysql服務器,準備數據庫賬號密碼

下載mysql c庫官方包

https://dev.mysql.com/downloads/installer/
在這裏插入圖片描述

新建目錄 clib 放c++ 庫

在這裏插入圖片描述

main.cpp 中 #include “mysql.h”

  • 發現 報錯,
  • 先創建 c_cpp_properties.json文件
{
    "configurations": [
        {
            "name": "Win32",
            "includePath": [
                "${workspaceFolder}/**",
                "C:\\mingw32\\include",
                "D:\\CodeHome\\cpp\\myfirst\\first",
                "D:\\CodeHome\\cpp\\lib\\mysql\\include"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "compilerPath": "C:\\mingw32\\bin\\gcc.exe",
            "cStandard": "c11",
            "cppStandard": "c++17",
            "intelliSenseMode": "clang-x86"
        }
    ],
    "version": 4
}
  • 然後在tasks.json 中修改args 命令
{
    // See https://go.microsoft.com/fwlink/?LinkId=733558 
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "type": "shell",
            "label": "g++.exe build active file",
            "command": "C:\\mingw32\\bin\\g++.exe",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}\\${fileBasenameNoExtension}.exe",
                "-I", //包含頭目錄
                "D:\\CodeHome\\cpp\\myfirst\\first", //頭目錄路徑
                "D:\\CodeHome\\cpp\\myfirst\\first\\q.cpp", //不想一個個編譯成 .o文件,直接包含 cpp 文件
                "-I",
                "D:\\CodeHome\\cpp\\lib\\mysql\\include", // mysql頭文件,有順序要求,要求放在被導入文件之後,
                "-L",
                "D:\\CodeHome\\cpp\\lib\\mysql\\lib", // mysql 庫文件 dll
                "-llibmysql" // 導入那個庫
            ],
            "options": {
                "cwd": "C:\\mingw32\\bin"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": "build"
        }
    ]
}
  • 把 libmysql.dll dll 複製到 與 main.cpp 同一個目錄

在這裏插入圖片描述

  • 編寫代碼
#include <iostream>
//#include "q.h"
#include "mysql.h"

using namespace std;
int main()
{
    cout << "Hello, world!" << endl;
    // q1();
    MYSQL conn;
    int res;
    mysql_init(&conn);
    if (mysql_real_connect(&conn, "127.0.0.1", "root", "123", "test", 0, NULL, CLIENT_FOUND_ROWS)) //"root":數據庫管理員 ,:123密碼 "test":數據庫的名字
    {
        printf("connect success!\n");
        res = mysql_query(&conn, "insert into test values('user','123456')");
        if (res)
        {
            printf("error\n");
        }
        else
        {
            printf("OK\n");
        }
        mysql_close(&conn);
    }
    else
    {
        printf("connect errot!\n"); 
    }
    return 0;
}
  • f5 調試,輸出connect success, error 是因爲sql 命令錯誤
    在這裏插入圖片描述
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章