Loading...

Python / / 2022. 4. 29. 10:41

파이썬 3강. mariaDB 연결 insert

반응형

db연결을 위해 라이브러리 설치가 필요하다.

jdbc같은게 필요한것이다.

 

터미널 창을 열어 설치해주자.

python -m pip install pymysql

db 연결을 위해 5가지 인자가 기본이다.

from pymysql import connect, cursors

conn = connect(
    host="localhost",
    user="green",
    password="green1234",
    db="greendb",
    charset="utf8"
)

pymysql에서 charset에 utf8로 하이푼이 없는것에 주의하자.

 

cursor는 기본적으로 tuple 타입으로 반환해주는데 기본 파싱 전략을 dict으로 바꿔주자.

cursors = conn.cursor(cursors.DictCursor) # 기본 tuple

스프링에서는 :username으로 바인딩했고, 물음표로 했다.

얘는 변수자리에 문자열이든 숫자든 %s라고 적어준다.

execute는 버퍼로 쿼리를 전송해준다!

그리고 %s에 채워넣을 내용은 두번째 인자에 배열로 넣어준다.

insert_sql = "INSERT INTO my_member(username, password) VALUES(%s, %s)"
cursor.execute(insert_sql, ["love", "1234"])

마지막으로 커밋해주면 끝

트랜잭션 관리까지 가능하다.

conn.commit()

실행하여 아무런 메세지가 없다는 것은 성공적으로 실행되었다는 것이다.

 

db 연결을 어디서나 import만 해서 사용할 수 있게 모듈을 따로 만들어줄 것이다.

# import할 때마다 실행되는 모듈
from pymysql import connect, cursors

conn = connect(
    host="localhost",
    user="green",
    password="green1234",
    db="greendb",
    charset="utf8"
)

cursor = conn.cursor(cursors.DictCursor)  # 기본 tuple
from db import connect as db

insert_sql = "INSERT INTO my_member(username, password) VALUES(%s, %s)"
db.cursor.execute(insert_sql, ["love", "1234"])
db.conn.commit()

 

 

[출처]

 

https://cafe.naver.com/metacoding

 

메타코딩 : 네이버 카페

코린이들의 궁금증

cafe.naver.com

메타 코딩 유튜브

https://www.youtube.com/c/%EB%A9%94%ED%83%80%EC%BD%94%EB%94%A9

 

메타코딩

문의사항 : getinthere@naver.com 인스타그램 : https://www.instagram.com/meta4pm 깃헙 : https://github.com/codingspecialist 유료강좌 : https://www.easyupclass.com

www.youtube.com

 
반응형