考虑遵循c代码:
int main (int argc, char *argv[]) {
MYSQL *sql_handle;
fprintf(stdout,"initializing handle..\n");
sql_handle = mysql_init(sql_handle);
fprintf(stdout,"connecting to database..\n");
mysql_real_connect(sql_handle,NULL,NULL,
NULL,"test",0,NULL,0);
fprintf(stdout,"connection established\n");
mysql_close(sql_handle);
}
这会产生以下输出
...
initializing handle..
connecting to database..
initializing handle..
connecting to database..
initializing handle..
connecting to database..
initializing handle..
connecting to database..
connection established
Error: Can't create UNIX socket (24)
real_connect函数似乎有问题。守护进程肯定在运行。很久以前,因为我习惯了,所以这可能是一个愚蠢的问题。
[更新] 这是完整的代码
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 #if defined __WIN32__ || _MSC_VER
5 #include "my_global.h"
6 #include "mysql.h"
7 #else
8 #include <mysql.h>
9 #endif
10
11 /* prototypes */
12 void connect(void);
13
14 /* sql handle */
15 MYSQL *sql_handle;
16
17 int main (int argc, char *argv[]) {
18 fprintf(stdout,"main..\n");
19 connect();
20 return EXIT_SUCCESS;
21
22 }
23 void connect(void){
24 fprintf(stdout,"initializing database handle..\n");
25 sql_handle = mysql_init(NULL);
26
27 fprintf(stdout,"connecting to database..\n");
28 mysql_real_connect(sql_handle,NULL,NULL,NULL,NULL,0,NULL,0);
29
30 fprintf(stdout,"closing connection..\n");
31 mysql_close(sql_handle);
32 }
此代码生成该输出:
...
connecting to database..
initializing database handle..
connecting to database..
initializing database handle..
connecting to database..
closing connection..
[1] 12914 segmentation fault (core dumped) ./db
将connect-function的主体复制到main并删除connect-functions解决了这个问题。但这不是解决方案。
答案 0 :(得分:1)
重命名方法
void connect(void)
到
void connect_to_database(void)
为我解决了这个问题
答案 1 :(得分:1)
我认为问题出在函数connect()中,它与socket的connect()名称相同:
int connect(int sockfd,const struct sockaddr * addr,socklen_t addrlen);
链接时,函数mysql_real_connect()需要调用connect()来连接底层套接字,但是调用重新定义的connect()函数,因此生成了循环。
这就是为什么将connect()的名称更改为connect_to_database()解决了这个问题。
答案 2 :(得分:0)
我认为你需要一个真正的sql句柄对象
int main (int argc, char *argv[]) {
MYSQL *sql_handle;
/* create object */
sql_handle = malloc(sizeof *sql_handle);
/* ... */
/* release object */
free(sql_handle);
}
或
int main (int argc, char *argv[]) {
MYSQL sql_handle; /* create object, not pointer */
fprintf(stdout,"initializing handle..\n");
mysql_init(&sql_handle); /* use address */
fprintf(stdout,"connecting to database..\n");
mysql_real_connect(&sql_handle,NULL,NULL, /* use address */
NULL,"test",0,NULL,0);
fprintf(stdout,"connection established\n");
mysql_close(&sql_handle); /* use address */
}