简单封装MySQLdb模块操作MySQL数据库
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简单封装MySQLdb模块操作MySQL数据库相关的知识,希望对你有一定的参考价值。
python连接mysql的connector有很多,我们选择MySQLdb
让python支持MySQLdb模块
#pip2.7 install MySQL-python查看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-*- import MySQLdb //导入MySQL驱动原生模块 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() def find(self,field,db,table): //定义mysql中的Select查询语句 """ 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) ); ‘‘‘) def insert(self,db,table,*l): //插入数据 self.cur1.execute(‘insert into ‘+ db + ‘.‘ + table + ‘ values(null,%s,%s,%s)‘ , *l) self.conn1.commit()
本文出自 “Zcy.gy” 博客,请务必保留此出处http://1064187464.blog.51cto.com/9108437/1786179
以上是关于简单封装MySQLdb模块操作MySQL数据库的主要内容,如果未能解决你的问题,请参考以下文章
Python MySQLdb模块连接操作mysql数据库实例_python