본문 바로가기
Programming/데이터베이스

[MySQL] 파이썬에서 쿼리문 실행할 때 %d format 오류

by 조창대 2022. 9. 8.
반응형

mysql 로고

 

 

python과 MySQL을 연결하여 insert 쿼리문을 작성할 때 어처구니없는 오류와 마주해서 작성하는 글..

 

내 소스 코드는 이거였다.

config = {
    'host' : '127.0.0.1',
    'user' : '****',
    'passwd' : '****',
    'database' : 'test_db',
    'port' : 3306,
    'charset' : 'utf8',
    'use_unicode' : True
}

with pymysql.connect(**config) as conn:
    with conn.cursor() as cursor:
        sql = "insert into sales(sCode, sDate, Qty, Amt) values(%s, %s, %d, %0.2f)"
        cursor.executemany(sql, insert_val) # executemany의 매개변수는 튜플을 담은 리스트여야함.
        conn.commit()

*참고

insert_val --->  [('a001', datetime.datetime(2021, 7, 1, 0, 52, 30), 5, 500), ('a002', datetime.datetime(2021, 7, 11, 0,  52, 30), 5, 1000), ('a003', datetime.datetime(2021, 7, 13, 0, 52, 30), 3, 900), ('a007', datetime.datetime(2021, 7, 21, 0, 52, 30), 5, 3500), ('a009', datetime.datetime(2021, 7, 26, 0, 52, 30), 5, 4500), ('a010', datetime.datetime(2021, 7, 23, 0, 52, 30), 1, 1000)]

 

pymysql 모듈을 이용하여 mysql과 연동하고 실행할 쿼리문을 작성하였다.

나는 여러 개의 로우를 한 번에 insert 하고 싶어서 executemany의 인수로 insert_val를 넣었다.

근데 웬 걸... 이런 에러가 뜬다.

TypeError: %d format: a real number is required, not str

잉? insert_val의 요소들의 타입을 하나씩 프린트해보아도 내가 포맷을 잘못 입력한 게 없는데 왜 이럴까 2시간 고민했다.

%d 자리엔 insert_val[*][2] 값이 들어갈건데 여기 있는 값은 정수인데 왜 오류가 날까..?

 

 

열나게 구글링한 결과,

실행하려는 sql 에서의 %s는 파이썬에서 일반적으로 사용하는 문자열 포맷터가 아닌 placeholder 역할을 하는 아이였다.

즉, 들어가는 값이 정수라고 %d, 실수라고 %0.2f라고 쓰면 안된다.

insert하거나 select 등 쿼리에 삽입해야 하는 컬럼값이 execute 메서드의 두번째 인수에서 tuple의 형태로 지정되어 있을 때 쿼리문에선 %s는 단순 컬럼값을 대치하는 역할을 하는 아이이니 무조건 %s만 사용한다.

 

 

sql = "select * from sales where sCode = %s and Qty = %s"
cursor.execute(sql, ('a001',2))
rows = cursor.fetchall()

이걸 보면 이해가 파박 될거다.

 

 

* 수정한 코드

sql = "insert into sales(sCode, sDate, Qty, Amt) values(%s, %s, %s, %s)"
cursor.executemany(sql, insert_val)
conn.commit()

 

 

 

* 참고

https://stackoverflow.com/questions/5785154/python-mysqldb-issues-typeerror-d-format-a-number-is-required-not-str

 

Python MySQLdb issues (TypeError: %d format: a number is required, not str)

I am trying to do the following insert operation: cursor.execute(""" insert into tree (id,parent_id,level,description,code,start,end) values (%d,%d,%d,%s,%...

stackoverflow.com

 

반응형