Python

[mysql] Python - MySQL Update (데이터 수정)

7204

목차

  1. MySQL 데이터 수정 구문
  2. 테이블 UPDATE - 데이터 수정
  3. SQL Injection 방지 - %s 자리표시자

 

테이블 생성데이터 삽입 후, 실습 권장.

 

MySQL 데이터 수정 구문

 

WHERE 조건절 이용해 수정할 행을 선택 후, 컬럼 데이터 수정.

주의: WHERE 구문이 없으면 모든 레코드가 수정됨. 

(예)

UPDATE hz_member SET mb_level = '100' WHERE mb_level = '10' 


 

테이블 UPDATE - 데이터 수정

※ 10레벨을 100레벨로 변경.

 

import mysql.connector


mydb = mysql.connector.connect(

  host="localhost",

  user="root",

  password="autoset",

  database="hz"

)


mycursor = mydb.cursor()

sql = "UPDATE hz_member SET mb_level = '100' WHERE mb_level = '10'"

mycursor.execute(sql)

mydb.commit()

print(mycursor.rowcount, "record(s) affected")

 

※ 주의1: mydb.commit() 없으면 변화가 반영 X

※ 주의2: 위처럼 하면 해킹 당할 수 있으니, 아래처럼 사용 권장.

 

SQL Injection 방지 - %s 자리표시자

 

%s 자리표시자 사용해 SQL Injection 방지.

 


[예제] 10레벨을 100레벨로 변경.

 

import mysql.connector


mydb = mysql.connector.connect(

  host="localhost",

  user="root",

  password="autoset",

  database="hz"

)


mycursor = mydb.cursor()

sql = "UPDATE hz_member SET mb_level = %s WHERE mb_level = %s"

level = ("100", "10")

mycursor.execute(sql, level)

mydb.commit()

print(mycursor.rowcount, "record(s) affected")

 



분류 제목
mysql Python - MySQL Start (DB 사용)
mysql Python - MySQL Create Database (DB 생성)
mysql Python - MySQL Create Table (테이블 생성)
mysql Python - MySQL Insert Into Table (데이터 삽입)
mysql Python - MySQL Select From (데이터 선택)
mysql Python - MySQL Where (조건절)
mysql Python - MySQL Order By (정렬순서)
mysql Python - MySQL Delete From (데이터 삭제)
mysql Python - MySQL Drop Table (테이블 삭제)
mysql Python - MySQL Update (데이터 수정)
mysql Python - MySQL Limit (데이터 출력개수)
mysql Python - MySQL Join (테이블 결합)
목록
 홈  PC버전 로그인 일본어
그누앞단언어
그누뒷단언어
그외코딩언어
그누보드
제작의뢰
Q&A
커뮤니티 2
웹유틸
회원센터
홈짱닷컴 PC버전 로그인