관련 URL#
http://sourceforge.net/projects/mysql-python
데이터베이스 생성및 샘플 데이터 입력#
create database python;
CREATE TABLE `animals` (
`name` varchar(20) default NULL,
`species` varchar(20) default NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into `animals`(`name`,`species`) values ('Wallace','Walrus');
insert into `animals`(`name`,`species`) values ('Polly','Parrot');
insert into `animals`(`name`,`species`) values ('Freddie','Frog');
insert into `animals`(`name`,`species`) values ('Sammy','Skunk');
|
간단한 조회 애플리케이션#
데이터를 모두 가져와서 반복적으로 처리하기
# MySQL 모듈 import
import MySQLdb
# 데이터베이스 연결
db = MySQLdb.connect(host="localhost", user="root", passwd="c12345", db="python")
# 커서 생성
cursor = db.cursor()
# SQL구문 실행
cursor.execute("SELECT * FROM animals")
# 결과데이터를 튜플 형태로 추출
result = cursor.fetchall()
# 결과데이터를 반복적으로 처리
for record in result:
print record[0] , "-->", record[1]
|
데이터를 한건씩 가져와서 처리하기
# -*- coding: utf-8 -*-
# MySQL 모듈 import
import MySQLdb
# 데이터베이스 연결
db = MySQLdb.connect(host="localhost", user="root", passwd="c12345", db="python")
# 커서 생성
cursor = db.cursor()
# SQL구문 실행
cursor.execute("SELECT * FROM animals")
# 결과데이터의 총 갯수를 추출
numrows = int(cursor.rowcount)
# 한번에 한개의 데이터를 추출해서 표기
for x in range(0, numrows):
row = cursor.fetchone()
print row[0], "-->", row[1]
|
데이터를 제한된 건수만큼만 가져와서 처리하기
# -*- coding: utf-8 -*-
# MySQL 모듈 import
import MySQLdb
# 데이터베이스 연결
db = MySQLdb.connect(host="localhost", user="root", passwd="c12345", db="python")
# 커서 생성
cursor = db.cursor()
# SQL구문 실행
cursor.execute("SELECT * FROM animals")
# 추출한 결과 데이터를 3건으로 제한
result = cursor.fetchmany(3)
# 결과데이터를 반복적으로 처리
for record in result:
print record[0] , "-->", record[1]
|
트랜잭션#
- connection.begin() - 트랜잭션 시작
- connection.apilevel() - 현재 DB API레벨을 리턴
- connection.conv() - MySQL과 파이썬간의 타입 변환 옵션을 셋팅
- connection.commit() - 트랜잭션 커밋
- connection.rollback() - 트랜잭션 롤백
간단한 입력 애플리케이션#
# -*- coding: utf-8 -*-
# MySQL 모듈 import
import MySQLdb
# 데이터베이스 연결
db = MySQLdb.connect(host="localhost", user="root", passwd="c12345", db="python")
# 커서 생성
cursor = db.cursor()
# SQL구문 실행하기
cursor.execute("""INSERT INTO animals (name, species) VALUES ("Harry","Hamster")""")
cursor.connection.commit();
|
튜플을 이용하여 데이터 입력
# -*- coding: utf-8 -*-
# MySQL 모듈 import
import MySQLdb
name = raw_input("Please enter a name: ")
species = raw_input("Please enter a species: ")
# 데이터베이스 연결
db = MySQLdb.connect(host="localhost", user="root", passwd="c12345", db="python")
# 커서 생성
cursor = db.cursor()
# SQL구문 실행하기
cursor.execute("INSERT INTO animals (name, species) VALUES (%s, %s)",(name, species))
cursor.connection.commit();
|
튜플 리스트를 이용하여 데이터 입력
# -*- coding: utf-8 -*-
# MySQL 모듈 import
import MySQLdb
# 데이터베이스 연결
db = MySQLdb.connect(host="localhost", user="root", passwd="c12345", db="python")
# 커서 생성
cursor = db.cursor()
# SQL구문 실행하기
# dynamically generate SQL statements from list
cursor.executemany("INSERT INTO animals (name, species) VALUES (%s,%s)",
[('Rollo', 'Rat'), ('Dudley', 'Dolphin'), ('Mark', 'Marmoset')])
cursor.connection.commit();
|
간단한 수정 애플리케이션#
# -*- coding: utf-8 -*-
# MySQL 모듈 import
import MySQLdb
# 데이터베이스 연결
db = MySQLdb.connect(host="localhost", user="root", passwd="c12345", db="python")
# 커서 생성
cursor = db.cursor()
# SQL구문 실행하기
cursor.execute("UPDATE animals SET species=%s WHERE name=%s",('TEST', 'Rollo'))
cursor.connection.commit();
|
간단한 삭제 애플리케이션#
# -*- coding: utf-8 -*-
# MySQL 모듈 import
import MySQLdb
# 데이터베이스 연결
db = MySQLdb.connect(host="localhost", user="root", passwd="c12345", db="python")
# 커서 생성
cursor = db.cursor()
# SQL구문 실행하기
cursor.execute("DELETE FROM animals WHERE name=%s", 'Rollo')
cursor.connection.commit();
|
Add new attachment
Only authorized users are allowed to upload new attachments.
«
This page (revision-5) was last changed on
05-Oct-2008 17:14 by DongGukLee