簡單封裝MySQLdb模組操作MySQL資料庫

來源:互聯網
上載者:User

標籤:mysqldb   資料庫   python   

  1. python串連mysql的connector有很多,我們選擇MySQLdb

  2. 讓python支援MySQLdb模組

#pip2.7 install MySQL-python
查看python2.7可使用的模組是否存在MySQLdb
# ipythonWARNING: IPython History requires SQLite, your history will not be savedPython 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 = hostself.port = portself.user = userself.passwd = passwdself.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 fielddb -> query databasetable -> query table"""self.field = fieldself.db = dbself.table = tableself.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/1786181

簡單封裝MySQLdb模組操作MySQL資料庫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.