개발 일지
[Mysql] 데이터 insert 후 PK 얻기 (LAST_INSERT_ID()) 본문
데이터베이스에 새로운 데이터를 삽입하는 경우, 타 쿼리문 혹은 로직에서 삽입된 데이터의 pk를 사용해야하는 경우가 있다. 하지만 pk는 대부분 auto increament를 사용하여 테이블에 삽입되는 순간 지정되기 때문에 삽입후에 해당 테이블에서 다시 가져와야한다. 이때 LAST_INSERT_ID()를 사용하면 조금 더 편하게 해당 pk 값을 가져올 수 있다.
LAST_INSERT_ID()란 가장 최근에 성공적으로 수행된 INSERT 구문의 첫번째 AUTO_INCREMENT column의 값을 반환하는 mysql 함수이다.
여기서 유의해야할 부분은 해당 함수가 반환하는 값이 INSERT 구문의 첫번째 AUTO_INCREMENT column의 값이라는 점인데 이 말은 곧 하나의 쿼리문에서 여러개의 row를 insert하는 경우에는 해당 row 중 첫번째 행의 AUTO_INCREMENT column 값이 반환된다는 것이다. 즉 LAST_INSERT_ID() 함수는 마지막으로 insert된 pk 값을 리턴하는 것이 아니라 실행된 insert 구문 당 첫번째로 insert된 행의 pk 값을 반환한다.
따라서 쿼리문의 구조에 따라 의도한 것과는 다른 값이 반환될 수 있음을 인지하고 사용하는 것이 중요하다.
LAST_INSERT_ID()는 다음과 같이 사용할 수 있다.
create table user (
user_idx int not null auto_increament,
user_name varchar not null,
user_age tinyint not null,
primary key (user_idx)
);
insert into user (user_name, user_age)
values ('aaa', 20);
select last_insert_id();
pymysql에서의 활용
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
def user_info(user_name, user_age):
sql = '''insert into user (user_name, user_age)
values (%s, %s)'''
sql1 = '''select last_insert_id()'''
conn = pymysql.connect(db연결)
cursor = conn.cursor()
cursor.execute(sql, (user_name, user_age))
conn.commit()
cursor.execute(sql1)
result = cursor.fetchone() #user pk value
conn.close()
return result[0]
|
cs |
참고
https://cirius.tistory.com/1139
https://blog.leocat.kr/notes/2017/07/22/mysql-ibatis-fetch-pk-after-insert
'db > mysql' 카테고리의 다른 글
| [pymysql] Parameter Placeholder (0) | 2020.11.12 |
|---|