롸?
DB연동 (mariaDB) 본문
1. MySqldb 모듈
python에서 mairaDB를 사용하기 위해서는 이를 위한 모듈을 먼저 설치한다.
pip install mysqlclient
2. DB 연결
python에서 db연결은 다소 간단한 편이다. 모듈을 설치하면 import MySQLdb을 한 후 connect 메소드로 db와 연결을 하고 cursor객체를 얻어서 db를 조회한다. 연결정보를 넘겨주는 방법이 여러가지가 있다.
1) connect에 인자로 연결정보 넣기
conn = MySQLdb.connect(host='127.0.0.1', user='root', password='123', database='test')
cursor = conn.cursor()
2) dict 변수에 연결 정보 넣기
config = {
'host':'127.0.0.1',
'user':'root',
'password':'123',
'database':'test',
'port':3306,
'charset':'utf8',
'use_unicode':True
}
conn = MySQLdb.connect(**config)
cursor = conn.cursor()
3) 외부파일에서 연결 정보 가져오기
import MySQLdb
import ast
with open('db연결정보.txt', 'r') as con:
config = ast.literal_eval(con.read())
conn = MySQLdb.connect(**config)
cursor = conn.cursor()
3. sql문 작성 및 데이터 받아보기
커서객체까지 얻었다면 이제 sql문을 작성한 변수를 만들고 이를 execute한 후 fetchall이나 fetchone을 해주면 된다. insert, update, delete의 경우에는 autocommit이 아니기 때문에 commit(conn.commit())까지 실행해주면 된다.
sql = 'select * from datas'
#출력방법 1
for data in cursor.fetchall():
print('%s %s %s %s'%data)
#출력방법 2
for r in cursor:
print(r[0], r[1], r[2], r[3])
#출력방법 3
for (a, b, c, d) in cursor:
print(a, b, c, d)
#부분 자료 읽기
code = 3
sql = 'select * from datas where code=%s'
cursor.execute(sql, (code, )) #조건 값은 튜플로 주어야 함
sql = "select * from datas where code='{0}'".format(code)
cursor.execute(sql)
for data in cursor.fetchall():
print('%s %s %s %s'%data)
'프로그래밍 > Python' 카테고리의 다른 글
소켓과 스레드를 이용한 간단 에코서버, 챗 서버 (0) | 2020.05.13 |
---|---|
파일 입출력 (0) | 2020.05.13 |
모듈 (0) | 2020.05.08 |
클래스 (0) | 2020.05.08 |
함수, lambda (0) | 2020.05.07 |
Comments