top of page
  • Subham Das

Login System using Python and MySQL

Here we are working with a login system where all the data is automatically stored in our database MySQL. For using MySQL we are using an external module named 'mysql.connector'. You can also use sqlite3 instead MySQL. One part of the code also deals with Exceptional Handling. Actually I am creating a database using different Exceptions. You can also manually create your database but I considered about the worst case possible that is the reason of using Exceptional Handling. It will create a database name 'login' and a table name 'main' inside the database if it doesn't exist. This is the benefit of my code.


# Login System using Python and MySQL


import mysql.connector as sql


def login() :


db = sql.connect(host = "localhost", user = "root", passwd = "")

cur = db.cursor()


try :

cur.execute("create database login")

db = sql.connect(host = "localhost", user = "root", passwd = "", database = "login")

cur = db.cursor()


except sql.errors.DatabaseError :

db = sql.connect(host = "localhost", user = "root", passwd = "", database = "login")

cur = db.cursor()


try :

cur.execute("create table main(username varchar(50), NOT NULL, password int NOT NULL)")

except sql.errors.ProgrammingError :

pass


finally :

try :

cur.execute("create table main(username varchar(50) NOT NULL, password int NOT NULL)")

except sql.errors.ProgrammingError :

pass


while True :


flag = 0

user = input("Enter Username :")

passwd = int(input("Enter Password :"))


cur.execute("select * from main where username = '%s' and password = %s" % (user, passwd))

rud = cur.fetchall()


if rud :

print("Welcome")

flag = 1

if flag == 1 :

break


else :

cur.execute("insert into main values('{}', {})". format(str(user), passwd))

db.commit()

print("Account Created")

flag = 1

if flag == 1 :

break


cur.close()

db.close()


login()


1,750 views0 comments
logo12.PNG
bottom of page