新建类封装数据库增删改查封装若干个方法

import pymysql

class DATABASE:

    def __init__(self,host,port,user,passwd,db,charset="utf8"):

        self.host=host

        self.port=port

        self.user=user

        self.passwd=passwd

        self.db=db

        self.charset=charset



#self.conn=pymysql.connect(host=self.host,port=self.port,user=self.user,passwd=self.passwd,db=self.db,charset=self.charset)

        #self.cursor=self.conn.cursor()

    def connectDB(self):

        print("连接数据库....")



self.conn=pymysql.connect(host=self.host,port=self.port,user=self.user,passwd=self.passwd,db=self.db,charset=self.charset)

        self.cursor=self.conn.cursor()

        print("连接数据库成功")

    def disConnectDB(self):

        print("关闭库连接....")

        # 关闭游标

        self.cursor.close()

        # 提交事务

        self.conn.commit()

        # 关闭数据库连接

        self.conn.close()

        print("数据库连接已关闭!")

    def execute_sql(self,sql):

        self.connectDB()

        if sql[:6]=="select":

            """查询select """

            self.cursor.execute(sql)

            datas = self.cursor.fetchall()

            print("共%s条数据。" %len(datas))

        elif sql[:6]=="insert":

            datas=self.cursor.execute(sql)

            print("插入语句受影响的行数:", datas)

        elif sql[:6]=="update":

            datas=self.cursor.execute(sql)

            print("修改语句受影响的行数:", datas)

        elif sql[:6]=="delete":

            datas=self.cursor.execute(sql)

            print("删除语句受影响的行数: ",datas)

        else:

            datas=None

        self.disConnectDB()

        return datas

if __name__=="__main__":

    db=DATABASE("192.168.202.133",3306,"root","123123","grdb","utf8")

    sql_select="select * from user "

    print(db.execute_sql(sql_select))

sql_insert="insert into user values(555,'tom555','tom555','1989-03-17')"

    print(db.execute_sql(sql_insert))

sql_update="update user set birthday='2100-08-12' where name='lucy0'"

    print(db.execute_sql(sql_update))

    sql_delete="delete from user where name='lucy1'"

    print(db.execute_sql(sql_delete))

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.数据库简介 人类在进化的过程中,创造了数字、文字、符号等来进行数据的记录,但是承受着认知能力和创造能力的提升,...
    大熊_7d48阅读 563评论 0 1
  • 1、安装mysql模块 python2 ubuntu16.4环境下安装 先安装依赖,否则安装mysql-pytho...
    郭强成就阅读 216评论 0 1
  • import MySQLdb class MysqlSearch(object): def __init__(se...
    hearys阅读 1,178评论 0 0
  • 数据库编程概述、pymysql基本操作方法总结、参数化列表防止SQL注入总结 2.6 Python数据库编程 学习...
    Cestine阅读 1,615评论 0 2
  • 一、Python简介和环境搭建以及pip的安装 4课时实验课主要内容 【Python简介】: Python 是一个...
    _小老虎_阅读 5,820评论 0 10