成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

pyspider - python這個(gè)類中的方法到底有什么用處啊

瀏覽:104日期:2022-08-27 10:12:02

問(wèn)題描述

class BaseDB: ’’’ BaseDB dbcur should be overwirte ’’’ __tablename__ = None placeholder = ’%s’ maxlimit = -1 @staticmethod def escape(string):return ’`%s`’ % string @property def dbcur(self):raise NotImplementedError

escape函數(shù)是干什么的,看起來(lái)像是返回一段字符串dbcur怎么用來(lái)調(diào)用的呢,上面說(shuō)dbcur應(yīng)該重寫(xiě),在子類中重寫(xiě)嗎,然后怎么調(diào)用啊

pyspider代碼https://github.com/binux/pysp...

問(wèn)題解答

回答1:

escape 是給string添加``符號(hào)。比如你創(chuàng)建的table或者column里有空白字符時(shí)。

create table `hello world tb` (`column name1` INT NOT NULL AUTO_INCREMENT PRIMARY KEY)

錯(cuò)誤的查詢:select column name1 from hello world tb正確的查詢:select `column name1` from `hello world tb`

dbcur這個(gè)函數(shù)拋出未實(shí)現(xiàn)這個(gè)異常,目的是為了充當(dāng)接口,由子類去實(shí)現(xiàn)。Python里面沒(méi)有接口這個(gè)概念,所以定義接口時(shí),可以采用這種方式。DbBase只付責(zé)構(gòu)建sql語(yǔ)句,具體使用何種數(shù)據(jù)庫(kù)由子類實(shí)現(xiàn),好處是可以適配不同的數(shù)據(jù)庫(kù)。

源碼:

if __name__ == '__main__': import sqlite3 class DB(BaseDB):__tablename__ = 'test'placeholder = '?'def __init__(self): self.conn = sqlite3.connect(':memory:') cursor = self.conn.cursor() cursor.execute(’’’CREATE TABLE `%s` (id INTEGER PRIMARY KEY AUTOINCREMENT, name, age)’’’% self.__tablename__ )@propertydef dbcur(self): return self.conn.cursor()

標(biāo)簽: Python 編程
相關(guān)文章: