# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: Database.py Author : LiSen Date: 2018/6/26 15:51: ------------------------------------------------- """ ''' database 两个库:1、MySQLdb:只能python2版本用 2、PyMySQL:python2.3通用 Oracle:cx_Oracle ''' import MySQLdb import pymysql import cx_Oracle
instance = {} def singleton_mode(cls): def incall(*args,**kwargs): if cls not in instance: instance[cls] = cls(*args,**kwargs) return instance[cls] return incall
@singleton_mode class Mysql(object): def __init__(self, host, user, password, db, port, charset): self.connect = MySQLdb.Connect( host=host, user=user, passwd=password, db=db, port=port, # 3306 3308 整数 charset=charset) # charset=utf8 self.cursor = self.connect.cursor() # 游标 def change_data(self, sql): # 修改数据 self.cursor.execute(sql) self.connect.commit() # 提交 def search_data(self, sql): # 查找数据 self.cursor.execute(sql) return self.cursor.fetchall() # 返回数据,以元组套元组的形式返回。 def close(self): # 关闭接口 self.cursor.close() # 在栈内存中存放,先进后出 self.connect.close() # 连接对象 if __name__ == '__main__': db = Mysql('127.0.0.1', 'root', '123456', 'bob', 3306, charset='utf8') sql = "insert into user_info(user,password) values('bob','123456')" # db.change_data(sql) sql1 = "select * from user_info" data = db.search_data(sql1) print data