my sqlclient 를 통 해 MySQL 데이터 베 이 스 를 조작 합 니 다.

저 는 Python 3.5 를 사용 하기 때문에 my sqlclient 를 선택 하여 MySQL 을 조작 합 니 다.
mysqlclient 설치
python 이 my sql 을 조작 할 수 있 도록 하려 면 MySQLdb 드라이브 가 필요 합 니 다.python 이 my sql 을 조작 하 는 데 없어 서 는 안 될 모듈 입 니 다.
pip 설치 사용
pip install mysqlclient

테스트
테스트 는 매우 간단 합 니 다.MySQLdb 모듈 이 정상적으로 가 져 올 수 있 는 지 확인 하 십시오.
>>> import MySQLdb

오류 알림 없 음 MySQLdb 모듈 을 찾 을 수 없습니다.설치 설명 OK
python 조작 my sql 데이터베이스 기반
#coding=utf-8
import MySQLdb


#connect()             ,        :   ,  ,     。
#          ,             。
conn= MySQLdb.connect(
        host='localhost',
        port = 3306,
        user='root',
        passwd='123456',
        db ='test',
        )



#           conn  cursor()       。
cur = conn.cursor()

#     ,    cur   execute()       sql  。  execute()     sql          
cur.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))")

#      
cur.execute("insert into student values('2','Tom','3 year 2 class','9')")


#         
cur.execute("update student set class='3 year 1 class' where name = 'Tom'")

#         
cur.execute("delete from student where age='9'")

#cur.close()     
cur.close()

#conn.commit()       ,                    ,            。
conn.commit()

#conn.close()       
conn.close()

데이터 삽입
위의 execute()방법 에 순수한 sql 문 구 를 써 서 데 이 터 를 삽입 하 는 것 은 불편 합 니 다.예:
cur.execute("insert into student values('2','Tom','3 year 2 class','9')")

새로운 데 이 터 를 삽입 하려 면 이 문장의 값 을 수정 해 야 합 니 다.우 리 는 다음 과 같은 수정 을 할 수 있다.
#coding=utf-8
import MySQLdb

conn= MySQLdb.connect(
        host='localhost',
        port = 3306,
        user='root',
        passwd='123456',
        db ='test',
        )
cur = conn.cursor()

#      
sqli="insert into student values(%s,%s,%s,%s)"
cur.execute(sqli,('3','Huhu','2 year 1 class','7'))

cur.close()
conn.commit()
conn.close()

데이터 시트 에 한 번 에 여러 개의 값 을 삽입 하려 면?
#coding=utf-8
import MySQLdb

conn= MySQLdb.connect(
        host='localhost',
        port = 3306,
        user='root',
        passwd='123456',
        db ='test',
        )
cur = conn.cursor()

#        
sqli="insert into student values(%s,%s,%s,%s)"
cur.executemany(sqli,[
    ('3','Tom','1 year 1 class','6'),
    ('3','Jack','2 year 1 class','7'),
    ('3','Yaheng','2 year 2 class','7'),
    ])

cur.close()
conn.commit()
conn.close()
executemany()방법 은 한 번 에 여러 개의 값 을 삽입 하여 하나의 sql 문 구 를 실행 할 수 있 으 나 매개 변수 목록 의 매개 변 수 를 반복 하여 반환 값 은 영향 을 받 는 줄 수 입 니 다.
자세 한 내용 은 충 사의 원문 주 소 를 참조 하 시 오.

좋은 웹페이지 즐겨찾기