百分百源码网-让建站变得如此简单! 登录 注册 签到领金币!

主页 | 如何升级VIP | TAG标签

当前位置: 主页>网站教程>数据库> 数据是怎么存储在mysql?
分享文章到:

数据是怎么存储在mysql?

发布时间:08/01 来源:未知 浏览: 关键词:
mysql数据库能存储批量数据,个别将数据保留到MySQL中有两种方式,同步模式和异步模式。 我们都晓得mysql数据库能存储批量数据,但是你晓得数据是怎么存储在mysql中的吗?

同步模式

同步模式是采纳SQL语句,将数据插入到数据库中。但是要注意的是Scrapy的解析速度要弘远于MySQL的入库速度,当有批量解析的时候,MySQL的入库就可能会阻塞。

import MySQLdbclass MysqlPipeline(object):
    def __init__(self):
        self.conn = MySQLdb.connect('127.0.0.1','root','root','article_spider',charset="utf8",use_unicode=True)
        self.cursor = self.conn.cursor()    def process_item(self, item, spider):
        insert_sql = """
            insert into jobbole_article(title,create_date,url,url_object_id) VALUES (%s,%s,%s,%s)
        """
        self.cursor.execute(insert_sql,(item["title"],item["create_date"],item["url"],item["url_object_id"]))
        self.conn.commit()

异步模式

采纳同步模式可能会发生阻塞,我们可以运用Twisted将MySQL的入库和解析酿成异步操纵,而不是简略的execute,commit同步操纵。

对于MySQL的配置,我们可以直接在配置文件配置数据库:

MYSQL_HOST = "127.0.0.1"
MYSQL_DBNAME = "article_spider"
MYSQL_USER = "root"MYSQL_PASSWORD = "root"

在settings中的配置,我们通过在pipeline中定义from_settings猎取settings对象,可以直接猎取settings配置文件中的值。

运用Twisted供给的异步容器连贯MySQL:

import MySQLdb
import MySQLdb.cursorsfrom twisted.enterprise
import adbapi

运用adbapi可以使mysqldb的一些操纵酿成异步化的操纵
运用cursors进行sql语句的施行和提交

代码局部:

class MysqlTwistedPipline(object):
    def __init__(self,dbpool):
        self.dbpool = dbpool    @classmethod
    def from_settings(cls,settings):
        dbparms = dict(
            host = settings["MYSQL_HOST"],
            db   = settings["MYSQL_DBNAME"],
            user = settings["MYSQL_USER"],
            passwd = settings["MYSQL_PASSWORD"],
            charset = 'utf8',
            cursorclass = MySQLdb.cursors.DictCursor,
            use_unicode=True,
        )
        dbpool = adbapi.ConnectionPool("MySQLdb",**dbparms)        return cls(dbpool)    def process_item(self, item, spider):
        #运用Twisted将mysql插入酿成异步施行
        #runInteraction可以将传入的函数酿成异步的
        query = self.dbpool.runInteraction(self.do_insert,item)        #处置异样
        query.addErrback(self.handle_error,item,spider)    def handle_error(self,failure,item,spider):
        #处置异步插入的异样
        print(failure)    def do_insert(self,cursor,item):
        #会从dbpool掏出cursor
        #施行概括的插入
        insert_sql = """
                    insert into jobbole_article(title,create_date,url,url_object_id) VALUES (%s,%s,%s,%s)
                """
        cursor.execute(insert_sql, (item["title"], item["create_date"], item["url"], item["url_object_id"]))       #拿传进的cursor进行施行,而且主动完成commit操纵

以上代码局部,除了do_insert以外,其它均可复用。

以上就是数据是怎么存储在mysql?的细致内容,更多请关注 百分百源码网 其它相干文章!

打赏

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

百分百源码网 建议打赏1~10元,土豪随意,感谢您的阅读!

共有150人阅读,期待你的评论!发表评论
昵称: 网址: 验证码: 点击我更换图片
最新评论

本文标签

广告赞助

能出一分力是一分吧!

订阅获得更多模板

本文标签

广告赞助

订阅获得更多模板