import cx_Oracle as cx import csv #flag是你的日期列在哪一列,默認第一列 def save_data(reader,info,table_data,flag =1): #目標:1、如果數據庫中沒有數據,那麼所有數據都插入 # 2、如果數據庫裏數據日期大於當前需要插入的數據日期,那麼不插入 for i, rows in enumerate(reader): rowsdata = '' if i > 0: for j in range(len(rows)): rowsdata += '\'' + rows[j] + '\',' #構造values('','','',) rowsdata = rowsdata[:-1] #去掉末尾的 , if info[0][0] is None or info[0][0] < int(rows[flag - 1]): #參照【目標】,info[0][0]就是數據庫裏最大的,參考file_addr函數的sql cursor.execute("insert into " + table_data + " values( " + rowsdata + ")") #執行導入 conn.commit() def file_addr(): # 有其他表直接再新增函數就可以 f = open('E:/shuju/3.csv') reader = csv.reader(f) sql = 'select max(oc_date) from reportdata.dw_data_hy' cursor.execute(sql) info = cursor.fetchall() save_data(reader,info,table_data,flag=2) #如果不是第一列,在這裏加flag f.close() if __name__ == '__main__': table_data = 'dw_data_hy' #表名 username = 'reportdata' #數據庫名 passwd = 'reportdata' #數據庫密碼 host = 'localhost' # ip port = '1521' # 端口 sid = 'orcl' #數據庫實例名 tns = cx.makedsn(host,port,sid) #tns固定搭配 conn = cx.connect(username,passwd,tns) #數據庫連接 cursor = conn.cursor() #啓用遊標指針 file_addr() print('XXX數據導入成功!')