Create(생성), Read(읽기), Update(갱신), Delete(삭제)
데이터베이스 에서의 INSERT, SELECT, UPDATE, DELETE를 말한다.
host = 'IP주소(본인은 localhost 사용)'
user = 'MySQL ID'
password = 'MySQL password'
db = 'MySQL DB명'
import pymysql
conn = pymysql.connect(host='', user='',
password='', db='', charset='utf8')
try:
curs = conn.cursor()
sql = '''CREATE TABLE user (
id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
name varchar(255),
email varchar(255)
)
'''
curs.execute(sql)
conn.commit()
finally:
conn.close()
conn
: DB 서버에 연결하여 성공하면 커넥션 객체 반환curs
: DB에서 SQL문을 대신 실행해주고 결과를 반환해줄 커서 객체. 커서 객체에 DB 작업을 위한 함수가 포함되어 있음.sql
: SQL 명령문curs.execute(sql)
: SQL 명령문을 실행conn.commit()
: 데이터 저장conn.close()
: DB 사용 후 연결 끊기try, finally
: try에서 에러가 나도 finally문은 반드시 실행하기 위해 사용import pymysql
conn = pymysql.connect(host='', user='',
password='', db='', charset='utf8')
try:
curs = conn.cursor()
sql = "INSERT INTO user VALUES (%s, %s, %s)"
val = (1111, "kim", "google")
curs.execute(sql, val)
conn.commit()
finally:
conn.close()
%s
: 포맷 문자중 문자열val
: SQL문에 들어갈 변수import pymysql
conn = pymysql.connect(host='', user='',
password='', db='', charset='utf8')
try:
curs = conn.cursor()
sql = "INSERT INTO user VALUES (%s, %s, %s)"
curs.execute(sql, (2222, "Park", "google"))
curs.execute(sql, (3333, "Kim", "naver"))
curs.execute(sql, (4444, "Seo", "Yahoo"))
conn.commit()
finally:
conn.close()
import pymysql
conn = pymysql.connect(host='', user='',
password='', db='', charset='utf8')
try:
curs = conn.cursor()
sql = "SELECT * FROM user"
curs.execute(sql)
data = curs.fetchall()
print(data[0])
finally:
conn.close()
CODE 터미널에서 확인
MySQL Workbench에서 확인
curs.fetchall()
: 레코드를 배열 형식으로 저장.
import pymysql
conn = pymysql.connect(host='', user='',
password='', db='', charset='utf8')
try:
curs = conn.cursor()
sql = "SELECT * FROM user"
curs.execute(sql)
result = curs.fetchall()
conn.commit()
for i in result:
print(i)
finally:
conn.close()
앗 1111 kim이 소문자로 되어 있다. (kim → Kim)으로 update 먼저 하고 와야겠다.
import pymysql
conn = pymysql.connect(host='', user='',
password='', db='', charset='utf8')
try:
curs = conn.cursor()
sql = "SELECT * FROM user WHERE name=%s"
val = ("Kim")
curs.execute(sql, val)
result = curs.fetchall()
conn.commit()
for i in result:
print(i)
finally:
conn.close()
import pymysql
conn = pymysql.connect(host='', user='',
password='', db='', charset='utf8')
try:
curs = conn.cursor()
sql = "UPDATE user SET name=%s WHERE name=%s"
val = ("Kim", "kim")
curs.execute(sql, val)
conn.commit()
finally:
conn.close()
kim이 Kim으로 변경된 것 확인
import pymysql
conn = pymysql.connect(host='', user='',
password='', db='', charset='utf8')
try:
curs = conn.cursor()
sql = "DELETE FROM user WHERE name=%s"
val = ("Seo")
curs.execute(sql, val)
conn.commit()
finally:
conn.close()