0
votes

I'm running OS 11.1 Big Sur and updating an objective C program that uses the MySql C API (NOT the C Connector). I CAN connect to local MySql server from the command line using

/usr/local/mysql/bin/mysql --user=root --password=aPassword

but when my software tries to connect through the C API using mysql_real_connect(mSQLPtr, theHost, theLogin, thePass, theDatabase, 0, NULL, 0); it fails with

Failed to connect to database: Error: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (1)

I've read heaps of posts to try and fix it e.g. stopping and starting the server, checking that /tmp/mysql.sock file does exist after starting the server (AND IT DOES EXIST), and adding a my.cnf to the /etc folder. It contains:

[mysqld]

socket=/tmp/mysql.sock

[client]

socket=/tmp/mysql.sock

Nothing has worked so far. Can anyone offer any suggestions please.

Cheers Jeff

1

1 Answers

0
votes
#include <stdio.h>
#include <stdlib.h>
#include <mysql.h>

static char *host = "localhost";
static char *user = "user";
static char *pass = "password";
static char *db   = "mysql";
static char *socket = NULL;
unsigned int port = 3306;
unsigned int flags = 0;

/*
* brew install mysql-client
* export PATH=/usr/local/opt/mysql-client/bin:$PATH
* brew install mysql-connector-c++ (optional)
* gcc -o main $(mysql_config --cflags) main.c $(mysql_config --libs) -L/usr/local/opt/openssl/lib
*
* -L/usr/local/opt/openssl/lib is required if you get ld: library not found for -lssl error
*/
int main(int argc, char *argv[]) {
    MYSQL *con = mysql_init(NULL);
    
    if (!mysql_real_connect(con, host, user, pass, db, port, socket, flags)) {
        fprintf(stderr, "Error %s (%d)", mysql_error(con), mysql_errno(con));
        exit(1);
    }
    
    printf("Connected\n");
    
    return EXIT_SUCCESS;
}