def __init__(self, username, password, database, host): self.exit = Exit() self.geoip = GeoIP() try: self.con = pymysql.connect(user=username, passwd=password, db=database, host=host) self.cur = self.con.cursor() except: self.exit.database_connection_error()
class DBHandler: def __init__(self, username, password, database, host): self.exit = Exit() self.geoip = GeoIP() try: self.con = pymysql.connect(user=username, passwd=password, db=database, host=host) self.cur = self.con.cursor() except: self.exit.database_connection_error() def execute_commit(self, query): self.cur.execute(query) self.con.commit() def create_table_hosts(self): query = """ CREATE TABLE IF NOT EXISTS `hosts`( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, `ip` VARCHAR(15) COLLATE utf8_general_ci, `lng` DECIMAL(11,8), `lat` DECIMAL(10,8), PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci AUTO_INCREMENT=1 ; """ self.execute_commit(query) def ip_in_db(self, ip): query = "SELECT 1 FROM hosts WHERE ip='%s'" % ip self.cur.execute(query) if self.cur.fetchone() == 1: return True else: return False def create_new_host_entry(self, ip): query = "INSERT INTO hosts(ip, lng, lat) VALUES ('%s', '%f', '%f')" % (ip, self.geoip.get_longitude(ip), self.geoip.get_latitude(ip)) self.execute_commit(query)