python 使用mysql数据库

在博客 python scrapy爬取网站数据一 中采用mysql进行数据的保存,本篇对mysql操作做一个总结。
1、mysql python库安装
python能连接到mysql数据库需要使用库包 pymysql,安装该包有两种方式
1)命令行安装

pip3 install pymysql

2)pyCharm安装
一次点击”File—>settings—>Project—>Project interpreter”,点击 “+”,在搜索框中输入 pymysql,点击安装即可
安装pymysql

2、数据库增删改查

import pymysql

class DBMySQL:
    db = ''
    cursor = ''
    def openDB(self,host,port,username,password,dbschema):
        # self.db = pymysql.connect(host="127.0.0.1", port=3306, user="root", password="zhl", database="sgyy",charset='utf8')
        self.db = pymysql.connect(host=host, port=port, user=username, password=password, database=dbschema,charset = 'utf8')
        self.cursor = self.db.cursor()

    def search(self,sql):
        try:
            self.cursor.execute(sql)
            items = self.cursor.fetchall()
            return  items
        except:
            print("查询出错,出错SQL:%s" % sql)
            return []

    # 插入、修改、删除
    def execute(self,sql):
        try:
            self.cursor.execute(sql)
            self.db.commit()
        except:
            print("执行出错,事务回滚,出错SQL:%s" % sql)
            self.db.rollback()

    def closeDB(self):
        self.cursor.close()
        self.db.close()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风水月

从心底相信自己是成功的第一步

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值