Search code examples
c++sqlmariadbdatabase-connectioncreateprocess

check mariadb connection with c++ (without dependencies)


I got myself a programm where a user types in their mariadb credentials (username/password/port).

I now want the programm to check if this connection is working or if something is wrong.

Right now I am running processes with CreateProcess but since statements like mysql -u root -pwrongpassword will still run through without any errors, this doesn't work.

I want such a statement, or just a generic connection check, to return false when those credentials turn out as wrong.

Important here is that it has to work without any existing software on the target system (except mariadb if necessary for your solution).

What would be a solid practice for that task?


Solution

  • Reinventing the wheel (as suggested by Sam Varshavchik) is not a good idea: It's not just opening a socket, writing and reading data. Depending on the authentication options you have to support SSL/TLS and the various authentication methods (native password, ed25519, sha256_caching_password, sha256_password, gssapi/kerberos) which is quite complex.

    Since you mentioned that MariaDB is installed on your target system, you can use the mariadb client library (MariaDB Connector/C), which is also used by mysql command line client. It is installed together with the server package.

    #include <mysql.h>
    
    int check_connection(const char *user, const char *password, int port)
    {
      int rc= 0;
      MYSQL *mysql= mysql_init(NULL);
    
      if (mysql_real_connect(mysql, "localhost", user, password, NULL, port, NULL, 0))
        rc= 1;
    
      mysql_close(mysql);
      return rc;
    }
    

    Now you have to link your application against libmariadb.lib (dynamic linking) or mariadbclient.lib (static linking).