首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用python用新数据替换旧数据

问使用python用新数据替换旧数据
EN

Stack Overflow用户
提问于 2013-03-28 20:37:11
回答 1查看 1.5K关注 0票数 0

我有两张桌子TBL1和TBL2。

TBL1有2列id,nSql。

TBL2有3列:date、custId、userId。

我在TBL1中有17行,id从1到17。每个nSql都有一个SQL查询。

例如,nSql For

id == 1为:"select date, pId as custId, tId as userId from TBL3"

id == 2是:"select date, qId as custId, rId as userId from TBL4" ...

nSql结果始终是相同的3列。

下面的查询运行并将数据放入表TBL2中。如果TBL2中已经有当天的数据,我希望查询用新数据替换数据。如果TBL2中没有数据,我想以正常的方式放入数据。

例如,如果我在早上运行查询,如果我想在晚上再次运行它,我希望新数据替换当天的旧数据,因为每天都会将数据插入到TBL2中。

还需要注意的是,如果数据已经存在(如果是由同事运行的),我不希望当天有重复的数据。

我该怎么做呢?

谢谢。

(我是python的新手,如果有人能在步骤中解释并在代码中显示,我将不胜感激)

代码语言:javascript
复制
import MySQLdb

# Open connection
con = MySQLdb.Connection(host="localhost", user="root", passwd="root", db="test")

# create a cursor object 
cur = con.cursor()

selectStatement = ("select nSql from TBL1") 
cur.execute(selectStatement)
res = cur.fetchall()
for outerrow in res:
    nSql = outerrow[0]
    cur.execute(nSql)
    reslt = cur.fetchall()

    for row in reslt:
        date = row[0]
        custId = row[1]
        userId = row[2]
        insertStatement = ("insert into TBL2( date, custId, userId) values ('%s', %d, %d)" % (date, custId, userId))
        cur.execute(insertStatement)
        con.commit() 
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-03-28 20:39:39

时间戳(使用datetime)插入到表中的所有数据。在插入之前,从日期时间为今天的表中删除。

对于MySQL,您可以使用函数to_days() with day来获取日期时间是哪一天:https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_to-days

在插入新行时,now()将允许您使用与当前时间对应的日期时间值:https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_now

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15682025

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档