def open_data_base(self): try: self.con except Exception as e: logger.error( "There is a error in connecting database,we are fixing!") self.con = self.get_con() self.cursor = self.con.cursor()
def close(self): # 先提交事务后关闭 try: self.con.commit() self.cursor.close() self.con.close() logger.info("database was closed") except Exception as e: logger.error(e)
def select(self, key, data): if self.con is None: self.con = Dao.get_con() self.cursor = self.con.cursor() data = str(data) sql = "SELECT * FROM %s WHERE %s = ?" % (self.item['table'], key) try: rs = self.cursor.execute(sql, data) self.con.commit() # logger.info("select success") return self.cursor.fetchall() except sqlite3.Error as e: logger.error(e)
def exist(self, key, data): if self.con is None: self.con = Dao.get_con() self.cursor = self.con.cursor() data = str(data) sql = "SELECT * FROM %s WHERE %s = '%s'" % (self.item['table'], key, data) try: rs = self.cursor.execute(sql) print(self.cursor.rowcount) if rs.rowcount > 1: return True except sqlite3.Error as e: logger.error(e) return False
def func(selector, xpath, order=-1): rs = None try: rs = selector.xpath(xpath) except IndexError as e: logger.error("可能不存在,请检查\t" + e) rs = "" except Exception as e: logger.error(e) rs = "" finally: if rs and order >= 0: return rs[order] else: if not rs: return '' return rs
def update(self, key="", value="", **kwargs): for cell in kwargs.keys(): self.__setitem__(key=cell, value=kwargs[cell]) if self.con is None: self.con = Dao.get_con() self.cursor = self.con.cursor() temp = [] for cell in self.item['data'].keys(): temp.append('"%s" = "%s"' % (cell, sql_str(self.item['data'][cell]))) s = ' ,'.join(temp) sql = 'UPDATE %s SET %s WHERE "%s" = "%s"' % (self.item['table'], s, str(key), str(value)) try: self.cursor.execute(sql) self.con.commit() # logger.info('Update successed') except sqlite3.Error as e: logger.error("Update ERROR:" + e) logger.error((self.item['data']))
def insert_update(self, select, key="", value="", **kwargs): if self.con is None: self.con = Dao.get_con() self.cursor = self.con.cursor() sql = "SELECT %s FROM %s WHERE %s='%s'" % (select, kwargs['table'], key, value) try: rs = self.cursor.execute(sql).fetchall() if rs: data = str(rs[0][0]).split('\t') if str(kwargs['data'][select]) not in str(rs[0][0]): data.append(sql_str(kwargs['data'][select])) s = kwargs.copy() s['data'][select] = '\t'.join(data) self.update(key=key, value=value, table=s['table'], data=s['data']) else: self.insert(table=kwargs['table'], data=kwargs['data']) except sqlite3.Error as e: logger.error("insert_update EROOR " + str(kwargs)) logger.error(e)