简体   繁体   English

python中的MySQL。 插入查询不起作用

[英]MySQL in python. Insert query does not work

I have a problem with MySQL's INSERT query. 我对MySQL的INSERT查询有问题。

Here is my python code: 这是我的python代码:

import socket
import MySQLdb

    def create_db():
         db1 = MySQLdb.connect(host="localhost",user="root",passwd="root")
         cursor = db1.cursor()
         sql = 'CREATE DATABASE IF NOT EXISTS  env_data;'
         select_db = 'USE env_data'
         ins = "insert into env_data(cpu_usage, date, mem_usage) values('40%', '1999-01-01 11:11:11', '25%');"
         engine_db = "set sql_mode='NO_ENGINE_SUBSTITUTION'"
         us = 'CREATE TABLE IF NOT EXISTS env_data (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,date datetime NOT NULL,cpu_usage varchar(10) NOT NULL,mem_usage varchar(10) NOT NULL);'
         cursor.execute(select_db)
         cursor.execute(us)
         cursor.execute(engine_db)
         cursor.execute(ins)

After execution database and tables are created properly, but the insert not works. 执行后,将正确创建数据库和表,但是插入无效。 When I do this query in my mysql server it works, but from this python script - there are no inserts in cpu_usage, date, mem_usage. 当我在mysql服务器中执行此查询时,它可以工作,但是从此python脚本开始-cpu_usage,date,mem_usage中没有插入。

In the script I have also tried to do mysql_notes = 0 / mysql_notes = 1 . 在脚本中,我还尝试执行mysql_notes = 0 / mysql_notes = 1

Could please someone help me with this issue? 请问有人可以帮助我解决这个问题吗?

You have to add db1.commit() after the insert statements. 您必须在插入语句之后添加db1.commit() This works in mysql workbench/command line, because, it has an autocommit options which is set to true by default. 这在mysql工作台/命令行中有效,因为它具有自动提交选项,默认情况下设置为true Otherwise, you would have to do the same. 否则,您将必须执行相同操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM