无法插入MySQL数据库

时间:2018-03-14 11:17:50

标签: python mysql

我正在尝试使用以下代码在MySQL数据库中插入一些内容,即使我没有收到任何异常或错误,表user中也没有任何内容。在crusor.execute()中,我尝试使用单引号封装列名,而不使用反引号也没有对我有用。

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()

这是我用来制作表格的查询

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;

1 个答案:

答案 0 :(得分:2)

您没有提交交易。在self.cursor.execute语句执行self.connection.commit()之后或在创建连接时设置autocommit=True。例如:

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