我正在尝试使用以下代码在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;

最佳答案

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

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

关于python - 无法插入MySQL数据库,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49276375/

10-11 03:51