Python MySQLdb插入问题
在这里,我正在用Python编写一个简单的应用程序,它将监视我的cpu和ram的使用情况,并将其放入MySQL数据库中供将来处理。下面是我的代码:Python MySQLdb插入问题,python,mysql,exception,mysql-python,Python,Mysql,Exception,Mysql Python,在这里,我正在用Python编写一个简单的应用程序,它将监视我的cpu和ram的使用情况,并将其放入MySQL数据库中供将来处理。下面是我的代码: import MySQLdb import psutil connection = MySQLdb.connect(host="localhost", port=8888, user="root", passwd="root", db="monitoring", unix_socket="/Applications/MAMP/tmp/mysql/
import MySQLdb
import psutil
connection = MySQLdb.connect(host="localhost", port=8888, user="root", passwd="root", db="monitoring", unix_socket="/Applications/MAMP/tmp/mysql/mysql.sock")
c = connection.cursor()
while True:
usage = psutil.cpu_percent(interval=1)
c.execute("INSERT INTO cpu (usage) VALUES (%s)", (usage))
c.execute("SELECT * FROM cpu")
print c.fetchall()
这是我正在使用的图书馆
以下是MySQL数据库的转储:
--
-- Table structure for table `cpu`
--
CREATE TABLE `cpu` (
`id` int(12) NOT NULL AUTO_INCREMENT,
`usage` float NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=2 ;
但是,我无法在插入时修复此错误:
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'usage) VALUES (12.9)' at line 1")
有什么建议可以解决这个问题吗?
很抱歉,我是Python新手:)
提前感谢。这不是Python的问题。问题是
usage
在MySQL中是一个保留字。您应该将列的名称更改为其他名称,或者在代码中使用反勾号引用它:
c.execute("INSERT INTO cpu (`usage`) VALUES (%s)", (usage))
天哪,蟒蛇之母,我不知道这件事。在你修好后,它就像一个符咒。非常感谢你。