[MySQL C API] 5. 마지막 삽입행 ID 알아내기(Last inserted row id)
1. 소스코드
테이블에 저장된 마지막 행의 ID가 필요할 때가 있다.
'mysql_insert_id()' 함수로 마지막 행의 ID를 알 수 있다.
이 함수는 테이블의 열(컬럼)을 'AUTO_INCREMENT'로 정의했을때 사용가능하다.
#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, "mysql_init() failed \n");
exit(1);
}
if (mysql_real_connect(con, "localhost", "user01", "1q2w3e!", "testdb",
0, NULL, 0) == NULL) {
finish_with_error(con);
}
if(mysql_query(con, "DROP TABLE IF EXISTS Writers")) {
finish_with_error(con);
}
// Id 컬럼을 AUTO_INCERMENT로 선언
char *sql = "CREATE TABLE Writers
(Id INT PRIMARY KEY AUTO_INCREMENT, Name TEXT)";
if (mysql_query(con, sql)) {
finish_with_error(con);
}
// 테이블에 Data를 3개 넣는다
if (mysql_query(con, "INSERT INTO Writers(Name) VALUES('Leo Tolstoy')")) {
finish_with_error(con);
}
if (mysql_query(con, "INSERT INTO Writers(Name) VALUES('Jack')")) {
finish_with_error(con);
}
if (mysql_query(con, "INSERT INTO Writers(Name) VALUES('Balzac')")) {
finish_with_error(con);
}
// 마지막 삽입행 id 알아내기
int id = mysql_insert_id(con);
printf("The last inserted row id is : %d \n", id);
mysql_close(con);
exit(0);
}
'mysql_insert_id()'함수는 이전에 실행한 INSERT나 UPDATE Query문에서 AUTO_INCREMENT 컬럼이 생성한 값을 반환한다.
아래 링크를 참고하여 번역 및 수정함
http://zetcode.com/db/mysqlc/