模塊和包.MySQLdb

簡單介紹:python

此模塊兒主要用於Python連接MySQL數據庫的接口,基於C API實現mysql


安裝方法:linux

for linux: pip install MySQL-pythonweb

for linux: yum -y install MySQL-pythonsql


鏈接對象:數據庫

MySQLdb.connect(host='10.2.5.51', port=3306, user='root', passwd='root', db='pyweb', charset='utf8') -> connfetch

說明:建立並返回一個數據庫鏈接,GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'root' WITH GRANT OPTION;flush privileges;spa

conn.close() -> None.net

說明:關閉數據庫鏈接code


遊標對象:

conn.cursor() -> cursor

說明:獲取遊標對象

cursor.execute(query, args) -> long

說明:執行單條sql語句,接收的參數爲sql語句自己和使用的參數列表,返回值爲受影響的行數

cursor.executemany(query, args) -> long

說明:執行單條sql語句,可是重複執行參數列表裏的參數,返回受影響的行數

cursor.rowcount -> int

說明:只讀屬性,並返回執行excute/excutemany方法後影響的行數

cursor.fetchone() -> tuple

說明:返回一條結果行

cursor.fetchall() -> tuple

說明:接收所有的返回結果行

cursor.fetchmany(size=None) -> tuple

說明:接收size條返回結果行

cursor.callproc(procname, args) -> tuple

說明:用來執行存儲過程,接收的參數爲存儲過程名和參數列表,返回值爲受影響的行數

cursor.nextset()

說明:移動到下一個結果集

cursor.scroll(value, mode='relative') -> None

說明:mode='relative'則表示從當前所在行跳過value條,若是mode='absolute',則表示從結果集中的第一條跳過value條

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
#
# Authors: limanman
# OsChina: http://my.oschina.net/pydevops/
# Purpose:
#
"""
import pprint
import MySQLdb
# 導入鏈接池的類
from DBUtils.PooledDB import PooledDB
# 導入字典遊標類
from MySQLdb.cursors import DictCursor


class MySQL(object):

    __sql_pool = None

    # 從鏈接池中取鏈接
    def __get_sqlpool_connection(self):
        if not  self.__sql_pool:
            self.__sql_pool = PooledDB(
                creator=self.sql_interface,
                use_unicode=self.is_unicode,
                cursorclass=self.cursor_class,
                db=self.db,
                host=self.host,
                port=self.port,
                user=self.user,
                passwd=self.passwd,
                charset=self.charset,
                mincached=self.mincached,
                maxcached=self.maxcached,
                maxconnections=self.maxconnections)
        return self.__sql_pool.connection()

    def __init__(self, *args):
        (self.sql_interface, self.is_unicode, self.cursor_class, self.db,
         self.host, self.port, self.user, self.passwd, self.charset,
         self.mincached, self.maxcached, self.maxconnections) = args

        # 從鏈接池中取鏈接生成遊標
        self.__sql_conn = self.__get_sqlpool_connection()
        self.__sql_cursor = self.__sql_conn.cursor()

    # 執行SQL命令
    def mysql_get_all(self, sql_command, command_parameter=None):
        """Mysql get all returns.

            Args:
                sql_command      : sql command
                command_parameter: command parameter
            Returns:
                dict
        """
        if command_parameter:
            count = self.__sql_cursor.execute(sql_command, command_parameter)
        else:
            count = self.__sql_cursor.execute(sql_command)

        if count:
            result = self.__sql_cursor.fetchall()
        else:
            result = None

        return result

if __name__ == '__main__':
    mysql = MySQL(MySQLdb, False, DictCursor, 'ddns_server',
                  '.................................', 3306,
                  '.......', '........', 'utf8', 5, 20, 62 )
    sql_command = r"select mac from device_my where userid=(select id from `user` where username='ytest');"
    sql_commres = mysql.mysql_get_all(sql_command)
    pprint.pprint(sql_commres)
相關文章
相關標籤/搜索