我有两张桌子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的新手,如果有人能在步骤中解释并在代码中显示,我将不胜感激)
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() 发布于 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
https://stackoverflow.com/questions/15682025
复制相似问题