【问题标题】:Python MySql Insert not workingPython MySql插入不起作用
【发布时间】:2011-08-27 00:04:50
【问题描述】:

我正在使用 python MySQL API 从 python 程序连接到 Mysql 数据库。我从几天开始就面临一个问题。我无法将记录插入数据库并且不知道是什么原因。这是我将记录连接并插入数据库的方式。

db = MySQLdb.connect("localhost","root","padmaramulu","pdfsearch" )
cursor = db.cursor()
#cursor.execute("""CREATE TABLE IF NOT EXISTS documents (docid INT NOT NULL ,PRIMARY KEY(docid),docname CHAR(30)) engine=innodb""")
temp = "hello";number = 2;
cursor.execute( 'insert into documents(docid,docname) values("%d","%s")' % (number,temp) )
db.close()

为什么会这样?

【问题讨论】:

  • 您应该标记解决了您的问题的答案。写下该答案的人将获得当之无愧的加分,读者将立即知道该解决方案已被应用并有效。

标签: python mysql


【解决方案1】:

在关闭连接之前,你应该添加db.commit()

【讨论】:

  • 您也可以在脚本开始时使用 db.autocommit(True)。因为 MySQLdb 从 1.2.0 开始禁用自动提交
  • 非常感谢 .. 非常有帮助
  • @SRC 虽然您的解决方案确实有效,但它仅在开发时使用。在生产环境中,您应该始终管理自己的事务
  • 谢谢先生!在我读到这篇文章之前,我一直在挠头。非常感谢!
  • db.autocommit(True) 为我工作,但 db.commit 没有......直到......我意识到我输入了 db.commit 而不是 db.commit() 我忘记了括号最后——我真是个傻瓜
【解决方案2】:

如果你在 MySQL 中使用 InnoDB 引擎,你应该添加

db.commit() 

否则将您的 MySQL 引擎更改为 MyISAM 无需更改代码中的任何内容。

【讨论】:

    【解决方案3】:

    也许有人遇到了同样的问题,也许这有帮助,

    任意 2 个选项:

    一个。对于使用 MySqldb 的人:

    db.commit() 
    

    b.对于使用 Mysql 连接器的人:

    cnx.commit()
    

    在关闭 db 或 Mysql 连接器之前添加此代码:

    一个。示例:(Azure)

    import mysql.connector
    from mysql.connector import errorcode
    
    # Obtain connection string information from the portal
    config = {
      'host':'<mydemoserver>.mysql.database.azure.com',
      'user':'<myadmin>@<mydemoserver>',
      'password':'<mypassword>',
      'database':'<mydatabase>',
      'client_flags': [ClientFlag.SSL],
      'ssl_cert': '/var/wwww/html/DigiCertGlobalRootG2.crt.pem'
    }
    
    # Construct connection string
    try:
       conn = mysql.connector.connect(**config)
       print("Connection established")
    except mysql.connector.Error as err:
      if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print("Something is wrong with the user name or password")
      elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print("Database does not exist")
      else:
        print(err)
    else:
      cursor = conn.cursor()
    
      # Drop previous table of same name if one exists
      cursor.execute("DROP TABLE IF EXISTS inventory;")
      print("Finished dropping table (if existed).")
    
      # Create table
      cursor.execute("CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);")
      print("Finished creating table.")
    
      # Insert some data into table
      cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("banana", 150))
      print("Inserted",cursor.rowcount,"row(s) of data.")
      cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("orange", 154))
      print("Inserted",cursor.rowcount,"row(s) of data.")
      cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("apple", 100))
      print("Inserted",cursor.rowcount,"row(s) of data.")
    
      # Cleanup
      conn.commit()
      cursor.close()
      conn.close()
      print("Done.")
    

    b.示例:(Dev Mysql)

    from __future__ import print_function
    from datetime import date, datetime, timedelta
    import mysql.connector
    
    cnx = mysql.connector.connect(user='scott', database='employees')
    cursor = cnx.cursor()
    
    tomorrow = datetime.now().date() + timedelta(days=1)
    
    add_employee = ("INSERT INTO employees "
                   "(first_name, last_name, hire_date, gender, birth_date) "
                   "VALUES (%s, %s, %s, %s, %s)")
    add_salary = ("INSERT INTO salaries "
                  "(emp_no, salary, from_date, to_date) "
                  "VALUES (%(emp_no)s, %(salary)s, %(from_date)s, %(to_date)s)")
    
    data_employee = ('Geert', 'Vanderkelen', tomorrow, 'M', date(1977, 6, 14))
    
    # Insert new employee
    cursor.execute(add_employee, data_employee)
    emp_no = cursor.lastrowid
    
    # Insert salary information
    data_salary = {
      'emp_no': emp_no,
      'salary': 50000,
      'from_date': tomorrow,
      'to_date': date(9999, 1, 1),
    }
    cursor.execute(add_salary, data_salary)
    
    # Make sure data is committed to the database
    cnx.commit()
    
    cursor.close()
    cnx.close()
    

    【讨论】:

      【解决方案4】:

      我认为你的代码应该修复

      cursor.execute( 'insert into documents(docid,docname) values(%d, %s)', (number,temp) )
      

      然后你应该在关闭数据库连接之前添加db.commit()

      【讨论】:

        【解决方案5】:

        您可以像这样设置 python 自动提交数据库中的更改:

        db = MySQLdb.connect("localhost","root","padmaramulu","pdfsearch, autocommit=True")```
        

        【讨论】:

          猜你喜欢
          • 2016-02-18
          • 1970-01-01
          • 1970-01-01
          • 2013-11-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多