1

I can use mysql from terminal to query data and I try to connect to mysql server with C but here is some problem i don't know to fix but seems like version conflict.

#include <my_global.h>
#include <mysql.h>

int main(int argc, char **argv)
{
  MYSQL *conn;
  conn = mysql_init(NULL);
  if (conn == NULL) {
      printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
      exit(1);
}

// upper code works

// following don't work...
if (mysql_real_connect(conn, "localhost", "username", "password", NULL, 0, NULL, 0) == NULL)
{
  printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
  exit(1);
}
etc...

When I start this code message "Error 2002: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)" appears. Problem is that I don't have mysql.sock anywhere in computer but have /var/run/mysqld/mysqld.sock. In linker options I added /var/lib/libmysql.so and program compiles OK.

Is here any simple way to get this to work?

1 Answer 1

2

why not connecting directly to the socket?

mysql_real_connect(conn, "localhost", "username", "password",
                   NULL, 0, "/var/run/mysqld/mysqld.sock", 0)

I have no environment to test it right now, but I think it should work

To answer question in your comment:

I think its' because of your configuration, mysql's default configuration is to store socket at /tmp/mysql.sock, and it didn't find it there, you just specified your location of the socket, this is not a portable solution, it depends on purpose of your application

Sign up to request clarification or add additional context in comments.

4 Comments

WOW, man, thanks a million. My first connection ever to mysql from C now WORKS :)) Is this propper use and why I get those error?
U got the error because C was looking for the socket at the location /tmp/mysql.sock which doesn't exist.
But why would C looks to /tmp/mysql.sock? From where he got this information?
This can be a problem for deploying programs. So, after all I find solution. Here is possible to create link to /var/run/mysqld/mysqld.sock, copy this link to tmp/ and rename it to mysql.sock. Then everything works as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.