Python之操作MySQL數據庫

     1、安裝MySQL-python-1.2.3

     2、然後連接數據庫

     3、執行數據庫的增、刪、改、查

# -*- coding: utf-8 -*-

import logging
import MySQLdb
import config

def get_db_con():
    con = MySQLdb.connect(host="192.168.6.82", port=3306,
    user="root", passwd="123456",db="test")
    return con

def query_db(sql):
    con = get_db_con()
    cursor = con.cursor()
    cursor.execute(sql)
    data = cursor.fetchall()
    cursor.close()
    con.close()
    return data

def change_db(sql):
    con = get_db_con()
    cursor = con.cursor()
    try:
        cursor.execute(sql)
        logging.info(sql)
        con.commit()
    except Exception, e:
        con.rollback()
        logging.error(e.message)


if __name__ == "__main__":
    sqlA = "show tables"
    sqlB = "select * from tablename"
    #print change_db(sql)
    print sqlA
    print query_db(sqlA)
    print sqlB
    print query_db(sqlB)


發佈了236 篇原創文章 · 獲贊 45 · 訪問量 84萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章