본문 바로가기

python

python - 데이터 베이스 연동(SQLite) , 테이블 데이터 수정 및 삭제

테이블 데이터 수정시 사용하는 SQL문?

UPDATE (table 이름) SET (변경하고자하는 column 항목) = ? WHERE id = ? ( ?1, ?2 )

c.execute("UPDATE users SET username = ? WHERE id = ?",('niceman',2))

딕셔너리 형태 - UPDATE (table 이름) SET ( // 항목) = : name(key)

c.execute("UPDATE users SET username = :name WHERE id = :id",{"name":'goodman', "id": 5})

문자열 형태 - UPDATE (Table 이름) SET %s = > 문자열, 숫자도 넣을 수 있다.

c.execute("UPDATE users SET username = '%s' WHERE id = '%s'" %('Goodboy', 3))

중간 데이터 확인

for user in c.execute("SELECT * FROM users")
# table users 에서 모든 데이터 가져온 상태로 한라인씩 출력
	print(user)
 
 

튜플 형태로 한라인씩 출력된다.

c.execute("DELETE FROM users WHERE id = ?",(2,))

삭제

# Row Delete1
c.execute("DELETE FROM users WHERE id = ?",(2,))

#  Row Delete2
c.execute("DELETE FROM users WHERE id = :id", {"id":5})

#  Row Delete3
c.execute("DELETE FROM users WHERE id = '%s'" % (4) )

테이블 전체 데이터 삭제

print("users db deleted :", conn.execute("DELETE FROM users").rowcount, "rows")

전체 데이터 삭제하면 삭제된 row 갯수가 출력된다.