【问题标题】:Insert query for mysql databse for datetime data type in cherrypy在cherrypy中插入对mysql数据库的日期时间数据类型的查询
【发布时间】:2017-07-03 15:47:18
【问题描述】:

这是我的插入查询,它工作正常,

db = MySQLdb.connect(host="localhost",user="root",passwd="", db="databseFile")
cur = db.cursor()
    print "source_id is: ",srcId[0]
    cur.execute('INSERT into config(col_1,col_2) values("%s","%s")'%(detail_1,detail_2))
    db.commit()
    cur.close()

这里是如何在 python 中获取日期时间:

from datetime import datetime
currentTime=datetime.now().strftime('%Y-%m-%d %H:%M:%S')

我想将 currentTime 插入到我的配置表中。datetime 的数据类型是什么? 我在网上搜索过,但没有找到任何解决方案。我的问题是,如何编写插入查询以在数据库中插入日期时间(我使用的是cherrypy和mysql)。

我想要这样的东西:

cur.execute('INSERT into config(col_1,col_2,col_3) values("%s","%s","WhatToWriteHere???")'%(detail_1,detail_2, currentTime))

【问题讨论】:

  • 只要使用mysql内置的now()函数:INSERT INTO table (datefield) VALUES (NOW());

标签: python mysql python-2.7 datetime cherrypy


【解决方案1】:

您要查找的可能是 MySQL 中存在的内置函数 — NOW()。以下是您可以如何使用它:

cur.execute('INSERT INTO config(col_1, col_2, col_3) values("%s", "%s", NOW())' % (detail_1, detail_2))

附:通常,您会使用一些 ORM 以更干净和安全的方式与 DB 进行交互,而无需使用原始 SQL 查询。看看SQLAlchemy

【讨论】:

  • @webKnjaZ ..我不能,因为我的声誉低于 15
猜你喜欢
  • 2013-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-06
相关资源
最近更新 更多