python通用数据库连接_python连接数据库的几种方式!
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: Database.py
Author : LiSen
Date: 2018/6/26 15:51:
-------------------------------------------------
"""
'''
database
兩個(gè)庫: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 整數(shù)
charset=charset) # charset=utf8
self.cursor = self.connect.cursor() # 游標(biāo)
def change_data(self, sql): # 修改數(shù)據(jù)
self.cursor.execute(sql)
self.connect.commit() # 提交
def search_data(self, sql): # 查找數(shù)據(jù)
self.cursor.execute(sql)
return self.cursor.fetchall() # 返回?cái)?shù)據(jù),以元組套元組的形式返回。
def close(self): # 關(guān)閉接口
self.cursor.close() # 在棧內(nèi)存中存放,先進(jìn)后出
self.connect.close() # 連接對(duì)象
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
總結(jié)
以上是生活随笔為你收集整理的python通用数据库连接_python连接数据库的几种方式!的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql 重置密码模式_mysql--
- 下一篇: python序列操作函数有哪些_Pyth