python操作数据库 封装类
生活随笔
收集整理的這篇文章主要介紹了
python操作数据库 封装类
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
# -*- coding:utf-8 -*-
# Author:Hy
# @Time :2018/2/1610:24
import pymysql
# 封裝類
class MysqlHelp(object):
# 構造
def __init__(self, host, user, passwd, db, port=3306):
self.host = host
self.user = user
self.port = port
self.passwd = passwd
self.db = db
# 創建連接
def open_coon(self):
self.coon = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db)
self.cursor = self.coon.cursor()
# 關閉連接
def close(self):
self.cursor.close()
self.coon.cursor()
# 調用語句
def insert_delete_update(self, sql, params):
try:
self.open_coon()
self.cursor.execute(sql, params=[])
print("OK")
self.coon.commit()
self.close()
except Exception as erorr:
print(erorr)
# 查詢 接收全部的返回結果行
def select_fetchall(self, sql, params=[]):
try:
self.open_coon()
self.cursor.execute(sql, params)
results = self.cursor.fetchall()
self.coon.commit()
self.close()
return results
except Exception as erorr:
print(erorr)
# Author:Hy
# @Time :2018/2/1610:24
import pymysql
# 封裝類
class MysqlHelp(object):
# 構造
def __init__(self, host, user, passwd, db, port=3306):
self.host = host
self.user = user
self.port = port
self.passwd = passwd
self.db = db
# 創建連接
def open_coon(self):
self.coon = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db)
self.cursor = self.coon.cursor()
# 關閉連接
def close(self):
self.cursor.close()
self.coon.cursor()
# 調用語句
def insert_delete_update(self, sql, params):
try:
self.open_coon()
self.cursor.execute(sql, params=[])
print("OK")
self.coon.commit()
self.close()
except Exception as erorr:
print(erorr)
# 查詢 接收全部的返回結果行
def select_fetchall(self, sql, params=[]):
try:
self.open_coon()
self.cursor.execute(sql, params)
results = self.cursor.fetchall()
self.coon.commit()
self.close()
return results
except Exception as erorr:
print(erorr)
轉載于:https://www.cnblogs.com/hyn934/p/8874245.html
總結
以上是生活随笔為你收集整理的python操作数据库 封装类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MR/hive/shark/sparkS
- 下一篇: 外媒评出中国最美20个景点