# Database code for Python-based URL shortener

I had implemented a URL shortener with Python and a database. Please review the database part of the code. The idea is to create an MD5 hash of the URL in question and then store it in a database. The hex digits of the MD5 hash is then encoded with a large base encoding i.e base 62 encoding or base 128 encoding to do away with the long length of the hash. The rest of the code can be found on https://github.com/hirok19/URLShortener.

import pysqlite3
import hashlib
class DatabaseConnector:
cursor=None
conn=None
def __init__(self,path):
try:
self.conn = pysqlite3.connect(path)
self.cursor=self.conn.cursor()
except:
print("Unable to initialize database")

def createTable(self):
try:
self.cursor.execute("""CREATE TABLE IF NOT EXISTS urlTable (id,url)""")
except Exception as e:
print("Unable to create table")
print(e)

def insertURL(self,URL):
key=self.getKey(URL)
#print(type(key))
insert_stmt = ("INSERT INTO urlTable (id,url) VALUES ('{0}','{1}');")
statement=insert_stmt.format(key,URL)
#print(statement)
try:
if(self.getURLFromKey(key) is None):
self.cursor.execute(statement)
self.conn.commit()
print("Data inserted!")
else:
except Exception as e:
print("Unable to insert data")
print(e)
return None
return key
def getKey(self,URL):
hashedKey=hashlib.md5(URL.encode())
return hashedKey.hexdigest()

def getURLFromKey(self,key):
insert_stmt=("SELECT url from urlTable where id='{0}';")
statement=insert_stmt.format(key)
#print(statement)
try:
self.cursor.execute(statement)
rows = self.cursor.fetchall()
if(len(rows)>0):
return rows[0][0]
else:
return None

except Exception as e:
print("Unable to fetch URL")
print(e)
return None

• Please fix your indentation. The easiest way to post code is to paste it into the question editor, highlight it, and press Ctrl-K to mark it as a code block. – 200_success Feb 2 at 18:05
• Can you confirm that the code is working as expected? You're question has received a close vote because this isn't clear at the moment. Also, would you be able to put all the relevant code in the question? We can't reasonable read anything which isn't in the question, and we have to assume that external links will rot with time. – VisualMelon Feb 2 at 22:52
• @VisualMelon, How can I paste code that spans over a few files?. The code works as expected. – Suryasis Paul Feb 4 at 14:23
• @200_success. The indentation is fixed. – Suryasis Paul Feb 4 at 14:23
• Any relevant files can be included in separate code blocks, with a heading to indicate the filename, and a description of what the code in the file does. Basically, anything you want us to take into consideration must be in the question body itself somewhere; if nothing else is relevant then it's not a problem at it is. – VisualMelon Feb 4 at 14:25