※환경 

OS : Centos7 

Package : MariaDB, gcc컴파일러, VIM



1. vim 편집기를 연다.


#vim main.cpp


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <stdio.h>
#include <stdlib.h>
#include <mysql.h>
 
struct connection_details {
 
    char *server;
    char *user;
    char *password;
    char *database;
 
};
 
MYSQL* mysql_connection_setup(struct connection_details mysql_details) {
 
    MYSQL *connection = mysql_init(NULL);
 
    if(!mysql_real_connect(connection, mysql_details.server, mysql_details.user, mysql_details.password, mysql_details.database, 0NULL0)) {
 
        printf("Connection error : %s\n", mysql_error(connection));
        exit(1);
 
    }
    return connection;
}
 
MYSQL_RES* mysql_perform_query(MYSQL *connection, char *sql_query) {
 
    if(mysql_query(connection, sql_query)) {
 
        printf("MYSQL query error : %s\n", mysql_error(connection));
        exit(1);
 
    }
    return mysql_use_result(connection);
}
 
 
int main() {
 
    MYSQL *conn;
    MYSQL_RES *res;
    MYSQL_ROW row;
 
    struct connection_details mysqlD;
    mysqlD.server = "IP주소 or localhost";
    mysqlD.user = "아이디";
    mysqlD.password = "패스워드";
    mysqlD.database = "DB 이름";
 
    conn = mysql_connection_setup(mysqlD);
 
    res = mysql_perform_query(conn, "show tables");
 
    printf("MySQL Tables in mysql database:\n");
    while((row = mysql_fetch_row(res)) != NULL)
        printf("%s\n", row[0]);
 
    mysql_free_result(res);
    mysql_close(conn);
    return 0;
 
}
cs


2. 컴파일 및 실행


#gcc main.cpp -I/usr/include/mysql -L/usr/lib64/mysql -lmysqlclient


3. 결과 확인


#./a.out





<애로사항>


1. undefined reference to `mysql_init` 등등..



★Solution

gcc 컴파일할 때 뒤에 -lmysqlclient 만 붙여주면 해결



2. cannot find -lmysqlclient



★Solution

내 피시에서 libmysqlclient.so 가 어딨는지 찾아본 후 (/usr/lib64/mysql  or  /usr/lib/mysql) 그곳의 경로를 입력해주면 됨

ex) .... -L/usr/lib64/mysql .....



3. Connection error : Can't connect to MySQL server on 'IP주소' (111)



★Solution

  • MySQL은 기본적으로 외부 접속을 막아놓았기 때문에, 외부에서 접속시도를 할 때 발생하는 문제
  • 외부에서의 접근을 모두 허용하겠다는 방법이 있음(but. 보안상 취약할 수 있다.)

#mysql -u root -p

비밀번호 입력

>grant all privileges on *.* to 'root'@'%' identified by 'password';

>flush privileges;

  • 본인이 Iptables 또는 Firewall 같은 것들을 쓰고 있다면 포트번호를 열어주는 것은 기본
  • 테스트를 할 때는 외부접근을 차단하고 localhost로 테스트 해보는 것이 안전하다.