python - 无法插入MySQL数据库

标签 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;

最佳答案

您没有提交交易。在 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/

相关文章:

python - 如何将参数与函数对象相关联?

Python 梯度下降多项式回归

python - 重写 sqlalchemy 中的关系行为

Python:将 HTML 转换为 AsciiDoc

python - 如何添加 Kivy 目录以便 Sublime Text 可以使用 Kivy 语言进行编译?

mysql - 如何营造安全的本地开发环境?

mysql - linux 和 windows 上的 mysql 之间的区别

java - 错误 com.mysql.jdbc.exceptions.jdbc4.CommunicationsException : Communications link failure

mysql - 无法远程连接到在 EC2 实例(非 RDS)上运行的 MySQL 实例

mysql - Laravel 家园 : Base table not found