使用python读取数据库中的内容 & 把爬虫爬到的内容,存储在mysql数据库中

安装pymsql库
以管理员身份打开cmd,输入pip Install pymysql

import pymysql
#连接数据库
conn = pymysql.connect(hoost='localhost' , user='root' , password='password' , db='mycommodity' , charset='utf8')
# localhost连接本地数据库 user 用户名 password 密码 db数据库名称 charset 数据库编码格式

#创建游标对象
cursor = conn.cursor()    #cursor当前的程序到数据之间的连接

#组装sql语句 需要查询的MySQL语句
sql = 'select * from commodity'

#执行sql语句
cursor.execute(sql)

#处理结果集
#获取一条数据
one = cursor.fetchone()
print(one)
#获取多条数据 传入需要获取的数据的条数
many = cursor.fetchmany(3)
print(many)

#获取所有数据
all = cursor.fetchall()
#输出获取到的数据的数据类型
print(type(all))

#逐条输出获取到的数据类型及数据
for each in all:
    print(type(each),each)

#获取数据库表中列的参数
fields = cursor.description
head = []
#或取数据库中表头
for field in fields:
    head.append(field[0])
print(head)

#关闭所有的连接
#关闭游标
cursor.close()
#关闭数据库
conn.close()

1.连接数据库

定义一个MySQLCommand类来配置数据库连接参数,并定义一个connectMysql方法连接数据库。

import pymysql
# 用来操作数据库的类
class MySQLCommand(object):
    # 类的初始化
    def __init__(self):
        self.host = 'localhost'
        self.port = 3308  # 端口号
        self.user = 'root'  # 用户名
        self.password = "password"  # 密码
        self.db = "home"  # 库
        self.table = "home_list"  # 表

    # 链接数据库
    def connectMysql(self):
        try:
            self.conn = pymysql.connect(host=self.host, port=self.port, user=self.user,
                                        passwd=self.password, db=self.db, charset='utf8')
            self.cursor = self.conn.cursor()
        except:
            print('connect mysql error.')

2.插入数据

# 插入数据,插入之前先查询是否存在,如果存在就不再插入
    def insertData(self, my_dict):
        table = "home_list"  # 要操作的表格
        # 注意,这里查询的sql语句url=' %s '中%s的前后要有空格
        sqlExit = "SELECT url FROM home_list  WHERE url = ' %s '" % (my_dict['url'])
        res = self.cursor.execute(sqlExit)
        if res:  # res为查询到的数据条数如果大于0就代表数据已经存在
            print("数据已存在", res)
            return 0
        # 数据不存在才执行下面的插入操作
        try:
            cols = ', '.join(my_dict.keys())#用,分割
            values = '"," '.join(my_dict.values())
            sql = "INSERT INTO home_list (%s) VALUES (%s)" % (cols, '"' + values + '"')
            #拼装后的sql如下
            # INSERT INTO home_list (img_path, url, id, title) VALUES ("https://img.huxiucdn.com.jpg"," https://www.huxiu.com90.html"," 12"," ")
            try:
                result = self.cursor.execute(sql)
                insert_id = self.conn.insert_id()  # 插入成功后返回的id
                self.conn.commit()
                # 判断是否执行成功
                if result:
                    print("插入成功", insert_id)
                    return insert_id + 1
            except pymysql.Error as e:
                # 发生错误时回滚
                self.conn.rollback()
                # 主键唯一,无法插入
                if "key 'PRIMARY'" in e.args[1]:
                    print("数据已存在,未插入数据")
                else:
                    print("插入数据失败,原因 %d: %s" % (e.args[0], e.args[1]))
        except pymysql.Error as e:
            print("数据库错误,原因%d: %s" % (e.args[0], e.args[1]))

你可能感兴趣的:(使用python读取数据库中的内容 & 把爬虫爬到的内容,存储在mysql数据库中)