Sahil
Sahil

Reputation: 1413

Unable to insert into MySQL database

I am trying to insert something in the MySQL database using the following code, and even though I am not getting any exception or errors, there's nothing in the Table user. In crusor.execute() I tried encapsulating the column names with single quotes and without also using the backtacks nothing worked for me.

import MySQLdb as sql

class DataBaseInteraction:
    def __init__(self):
        shost = "127.0.0.1"
        suser = "root"
        spassword = ""
        sdb = "gui"
        connection = sql.connect(host=shost,
                         user=suser,
                         password=spassword,
                         db=sdb)

        try:
            self.cursor = connection.cursor()
            print("sucksess")
        except Exception as e:
            print("The Exception was" + str(e))

        self.createuser("UserName", "Name", "Email", "Password")

    def createuser(self, username, namee, password, email):
        print("reached here")
        try:
            self.cursor.execute("""INSERT INTO user (`UserName`, `Name`, `Email`, `Password`) VALUES ({},{},{},{})""".format(username,
                                                                                                                        namee,
                                                                                                                        email,
                                                                                                                        password))
            print("SuckSess")
        except Exception as e:
            print("Exception was "+str(e))


if __name__ == "__main__":
    a = DataBaseInteraction()

Here's the query I used to make the table

CREATE TABLE `user` (
  `id` int(11) NOT NULL,
  `UserName` varchar(255) NOT NULL,
  `Name` varchar(255) NOT NULL,
  `Email` varchar(255) NOT NULL,
  `Password` varchar(255) NOT NULL,
  `CreationDate` date DEFAULT NULL,
  `LoggedIn` tinyint(1) NOT NULL DEFAULT '0',
  `LatestLoginTime` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Upvotes: 0

Views: 778

Answers (1)

Gaur93
Gaur93

Reputation: 695

You are not committing the transaction. After self.cursor.execute statement do self.connection.commit() or set autocommit=True at the time of creating connection. Ex:

connection = sql.connect(host=shost,
                     user=suser,
                     password=spassword,
                     db=sdb,
                     autocommit=True)

Upvotes: 2

Related Questions