python实现操作数据库的方法封装

常见的数据库操作的方法封装:

import pymysql


class DbFunc():
    def __init__(self,host,port,user,pwd,name,charset):
        self.host = host
        self.port  = port
        self.user = user
        self.pwd = pwd
        self.name = name
        self.charset = charset
        self.sql = ""
        self.conn = None

    def  connectsql(self):
        #链接数据库
        try:
            self.conn = pymysql.connect(self.host, user=self.user, passwd=self.pwd, db=self.name)
            cursor = self.conn.cursor()
            print("数据库链接成功")
            return cursor
        except pymysql.Error as e:
            print(e)

    def get_one(self,sql):
        #获取符合sql语句中的第一条
        try:
            cur = self.connectsql()
            cur.execute(sql)
            return  cur.fetchone()
        except pymysql.Error as e:
            print(e)

    def get_all(self,sql):
        #获取符合sql语句的所有数据
        try:
            cur = self.connectsql()
            cur.execute(sql)
            return cur.fetchall()
        except pymysql.Error as e:
            print(e)

    def get_many(self,sql,n):
        #获取符合sql语句中的部分
        try:
            cur = self.connectsql()
            cur.execute(sql)
            return cur.fetchmany(n)
        except pymysql.Error as e:
            print(e)

    def update(self,sql):
        #更新数据库操作
        try:
            cur = self.connectsql()
            num = cur.execute(sql)
            self.conn.commit()
            return num
        except pymysql.Error as e :
            print(e)

    def alert_add(self,sql):
        #增加一列
        try:
            cur = self.connectsql()
            num = cur.execute(sql)
            self.conn.commit()
            return num
        except pymysql.Error as e:
            print(e)

    def alert_modify(self,sql):
        #更改一列的数据类型
        try:
            cur = self.connectsql()
            num = cur.execute(sql)
            self.conn.commit()
            return num
        except pymysql.Error as e:
            print(e)


if __name__ == '__main__':
    host = "127.0.0.1"
    port = "3306"
    user = "root"
    pwd = "Dy******5"
    name = "django_demo"
    charset = "utf-8"
    sql1 = "select * from booktest_heroinfo;"
    sql = "update booktest_heroinfo set actor_content='打大美女' where id=2;"
    sql2 = "alter table booktest_heroinfo add column actor_TV varchar(20);"
    sql3 = "alter table date_test modify sid varchar(30);"

    cursor = DbFunc(host,port,user,pwd,name,charset)
    # print(cursor.get_one(sql))
    # print(cursor.get_all(sql))
    # print(cursor.get_many(sql,2))
    # print(cursor.update(sql))
    # print(cursor.get_all(sql1))
    # print(cursor.alert_add(sql2))
    print(cursor.alert_modify(sql3))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值