简单介绍:
此模块儿主要用于Python链接MySQL数据库的接口,基于C API实现
安装方法:
for linux: pip install MySQL-python
for linux: yum -y install MySQL-python
连接对象:
MySQLdb.connect(host='10.2.5.51', port=3306, user='root', passwd='root', db='pyweb', charset='utf8') -> conn
说明:创建并返回一个数据库连接,GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'root' WITH GRANT OPTION;flush privileges;
conn.close() -> None
说明:关闭数据库连接
游标对象:
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)