[MySQL C API] 3. 테이블 생성 및 데이터 넣기(Creating and populating a table)
1. 사용자 계정 추가
$ mysql -u root -p
터미널 창에서 mysql을 루트 권한으로 실행한다.
mysql> CREATE USER user01@localhost IDENTIFIED BY '1q2w3e!';
유저 아이디 유저 비밀번호
밑줄로 된 부분(ID, PW)는 원하는대로 설정
'user01'이라는 계정이 생성된다.
2. 데이터베이스 접근 권한
mysql> GRANT ALL ON testdb.* to user01@localhost;
user01에게 testdb에 대한 모든 접근권한을 준다.
3. 소스코드
테이블을 생성하고 데이터를 넣는 예제
#include <my_global.h>
#include <mysql.h>
//#에러 출력 함수
void finish_with_error(MYSQL *con)
{
fprintf(stderr, "%s \n", mysql_error(con));
mysql_close(con);
exit(1);
}
int main(int argc, char **argv)
{
MYSQL *con = mysql_init(NULL);
if (con == NULL)
{
fprintf(stderr, "%s \n", mysql_error(con));
exit(1);
}
//#user01으로 testdb에 연결
if (mysql_real_connect(con, "localhost", "user01", "1q2w3e!",
"testdb", 0, NULL, 0) == NULL)
finish_with_error(con);
}
//#Cars라는 테이블이 있으면 DROP 시킨다
if (mysql_query(con, "DROP TABLE IF EXISTS Cars"))
{
finish_with_error(con);
}
//#Cars 테이블 생성
if (mysql_query(con, "CREATE TABLE Cars(Id INT, Name TEXT, Price INT)"))
{
finish_with_error(con);
}
//#Cars 테이블에 데이터 넣기
if (mysql_query(con, "INSERT INTO Cars VALUES(1, 'Hyundai', 8000)"))
{
finish_with_error(con);
}
if (mysql_query(con, "INSERT INTO Cars VALUES(1, 'Audi', 9000)"))
{
finish_with_error(con);
}
if (mysql_query(con, "INSERT INTO Cars VALUES(1, 'GM', 7000)"))
{
finish_with_error(con);
}
//#접속 종료
mysql_close(con);
exit(0);
}
4. 컴파일 후 실행 결과
컴파일 방법은 아래 링크를 참조한다.
http://dk-projects.tistory.com/8
MySQL을 실행하여 testdb 안에 생성된 테이블을 확인한다.
mysql> USE testdb;
mysql> SHOW TABLES;
+----------------------+
| Tables_in_testdb |
+----------------------+
| Cars |
+----------------------+
1 row in set (0.00 sec)
Cars 테이블의 모든 데이터를 선택한다.
mysql> SELECT * FROM Cars;
+------+--------------+----------+
| Id | Name | Price |
+------+--------------+----------+
| 1 | Hyundai | 8000 |
| 2 | Audi | 9000 |
| 3 | GM | 7000 |
+------+--------------+----------+
3 rows in set (0.00 sec)
아래 링크를 참고하여 번역 및 수정함
http://zetcode.com/db/mysqlc/