您的位置:首頁技術文章
文章詳情頁

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

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

問題描述

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函數是干什么的,看起來像是返回一段字符串dbcur怎么用來調用的呢,上面說dbcur應該重寫,在子類中重寫嗎,然后怎么調用啊

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

問題解答

回答1:

escape 是給string添加``符號。比如你創建的table或者column里有空白字符時。

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

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

dbcur這個函數拋出未實現這個異常,目的是為了充當接口,由子類去實現。Python里面沒有接口這個概念,所以定義接口時,可以采用這種方式。DbBase只付責構建sql語句,具體使用何種數據庫由子類實現,好處是可以適配不同的數據庫。

源碼:

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()

標簽: Python 編程
相關文章:
国产综合久久一区二区三区