0

I'm new to databases, so I wanted to make a program to perform simple queries in mysql with C++ in VS Code, in Windows 10. Last time I had problems with linking the library, and now it seems like I managed to fixed them. I have the following code taken from another source by adding my system configurations:

#include <iostream>
#include <windows.h>
#include "C:/Program Files/MySQL/MySQL Server 8.0/include/mysql.h"

int main(){
    MYSQL* conn;
    conn = mysql_init(0);
    conn = mysql_real_connect(conn, "localhost", "root", "password", "project", 0, NULL, 0);

    if(conn){
        std::cout << "Connected" << std::endl;
    } else {
        std::cout << "Not connected" << std::endl;
    }
}

When I compile it with the command g++ main.cpp -Wall -Werror -I "C:/Program Files/MySQL/MySQL Server 8.0/include" -L "C:/Program Files/MySQL/MySQL Server 8.0/lib" -lmysql, it compiles without reporting any errors. However, if I try to run it, the program simply terminates. I don't understand what problems could be. I suspect the problem might be with mysql connector, but as I said I'm new to it, so I still have doubts. So I would really appreciate it if you could help me out how I can proceed further.

I looked for similar questions, and they helped me only for linking to the library.

  • *it compiles without reporting any errors* -- That has no bearing on whether the program has logical bugs. Second, none of those `cout`'s get printed? Third, why are you assigning `conn` twice, effectively corrupting the value returned by the `mysql_init(0);` call? – PaulMcKenzie Nov 18 '22 at 21:26
  • Have you tried using a debugger? – Alan Birtles Nov 18 '22 at 21:51
  • [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Jesper Juhl Nov 18 '22 at 22:17
  • I took the code from ```https://stackoverflow.com/questions/60876194/vscode-c-mysql-h-undefined-reference-to-mysql-init4```. I just wanted to see if I can compile it first. Well, none of the messages from cout got printed. – Yoqub Davlatov Nov 19 '22 at 06:59

2 Answers2

0

Fixed it. Just had to add libmysql.dll in a folder with the main.cpp file. Thank you all for your advices.

-1

mysql_init can return NULL:

An initialized MYSQL* handler. NULL if there was insufficient memory to allocate a new object.

Wouldn't be safer to check its value before second call?