Python MySQL은 데이터베이스 테이블 변경 및 쿼리를 수행합니다.

巴扎黑
풀어 주다: 2017-05-14 14:17:53
원래의
1084명이 탐색했습니다.

이 글에서는 주로 데이터베이스 테이블 변경 및 쿼리를 위한 Python MySQL 관련 정보를 소개합니다. 도움이 필요한 친구들은

Python은 데이터베이스 테이블 변경 및 쿼리를 위해 MySQL에 연결합니다:

python mysql 삽입 삭제 쿼리:


#!/usr/bin/python 
 
import MySQLdb 
def doInsert(cursor,db): 
  #insert 
  # Prepare SQL query to INSERT a record into the database. 
  sql = "UPDATE EMPLOYEE SET AGE = AGE+1 WHERE SEX = '%c'" %('M') 
  try: 
    cursor.execute(sql) 
    db.commit() 
  except: 
    db.rollback() 
 
def do_query(cursor,db): 
  sql = "SELECT * FROM EMPLOYEE \ 
     WHERE INCOME > '%d'" % (1000) 
  try: 
    # Execute the SQL command 
    cursor.execute(sql) 
    # Fetch all the rows in a list of lists. 
    results = cursor.fetchall() 
    print 'resuts',cursor.rowcount 
    for row in results: 
      fname = row[0] 
      lname = row[1] 
      age = row[2] 
      sex = row[3] 
      income = row[4] 
      # Now print fetched result 
      print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \ 
          (fname, lname, age, sex, income ) 
  except: 
    print "Error: unable to fecth data" 
 
def do_delete(cursor,db): 
  sql = 'DELETE FROM EMPLOYEE WHERE AGE > {}'.format(20) 
  try: 
    cursor.execute(sql) 
    db.commit() 
  except: 
    db.rollback() 
 
def do_insert(cursor,db,firstname,lastname,age,sex,income): 
  sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \ 
    LAST_NAME, AGE, SEX, INCOME) \ 
    VALUES ('%s', '%s', '%d', '%c', '%d' )" % \ 
    (firstname,lastname,age,sex,income) 
  try: 
    cursor.execute(sql) 
    db.commit() 
  except: 
    db.rollback() 
  
# Open database connection 
# change this to your mysql account 
#connect(server,username,password,db_name) 
db = MySQLdb.connect("localhost","root","root","pydb" ) 
# prepare a cursor object using cursor() method 
cursor = db.cursor() 
do_query(cursor,db) 
doInsert(cursor,db) 
do_query(cursor,db) 
do_delete(cursor,db) 
do_query(cursor,db) 
do_insert(cursor,db,'hunter','xue',22,'M',2000) 
do_insert(cursor,db,'mary','yang',22,'f',5555) 
do_insert(cursor,db,'zhang','xue',32,'M',5000) 
do_insert(cursor,db,'hunter','xue',22,'M',333) 
do_query(cursor,db) 
# disconnect from server 
db.close()
로그인 후 복사

그런 다음 필요에 따라 캡슐화할 수 있습니다.

위 내용은 Python MySQL은 데이터베이스 테이블 변경 및 쿼리를 수행합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!