设为首页 加入收藏

TOP

简单封装MySQLdb模块操作MySQL数据库(一)
2017-04-07 10:26:51 】 浏览:420
Tags:简单 封装 MySQLdb 模块 操作 MySQL 数据库

1. python连接mysql的connector有很多,我们选择MySQLdb
2. 让python支持MySQLdb模块


#pip2.7 install MySQL-python


3. 查看python2.7可使用的模块是否存在MySQLdb
# ipython
WARNING: IPython History requires SQLite, your history will not be saved
Python 2.7.11 (default, Mar 10 2016, 09:45:30) 
Type "copyright", "credits" or "license" for more information.
 
IPython 4.1.2 -- An enhanced Interactive Python.
?        -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?  -> Details about 'object', use 'object??' for extra details.
In [1]: help('modules')
Please wait a moment while I gather a list of all available modules...
 
MySQLdb            calendar            marshal


4. 简单封装的模块,测试没问题
script-name:mysql-conn.py
#!/usr/bin/python27
#-*-coding:utf-8-*-
 
#导入MySQL驱动原生模块
import MySQLdb 
 
class mysqldb():
        #构造器设定初始值
    def __init__(self,host='192.168.17.1',port=4306,user='root',passwd='zcy'): 
        self.host = host
        self.port = port
        self.user = user
        self.passwd = passwd
        #实例一开始就具备了连接和游标属性
        self.conn1 = MySQLdb.connect(host=self.host,port=self.port,user=self.user,passwd=self.passwd) 
        self.cur1 = self.conn1.cursor()
         
        #定义mysql中的Select查询语句
    def find(self,field,db,table): 
        """
            field -> query field
            db -> query database
            table -> query table
        """
        self.field = field
        self.db = db
        self.table = table
        self.cur1.execute('select ' + self.field + ' from ' + self.db + '.' + self.table)
        return self.cur1.fetchall()
         
        #建库
    def createdb(self,db): 
        self.cur1.execute('create database if not exists ' + db)
           
            #建表
    def createtable(self,db,table):   
        self.conn1.select_db(db)
        self.cur1.execute(
        '''
            create table ''' + table + ''' (
                id int(5) not null primary key auto_increment,
                name char(10) not null,
                phone varchar(12) not null,
                class char(20)
            );         
        ''')
                 
                #插入数据
  &

首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇shell变量赋值与环境 下一篇单向散列函数的价值和具体实现的..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目