在Python中使用SQL来比较字段并相应地更新列

时间:2014-09-25 21:12:36

标签: python mysql sql

我有两张桌子:

1.source_table

2.target_table

我想检查源表中的x,y,z字段是否与target_table中的A,B,C字段匹配,

          IF yes:

                 Update values P,Q,R,S in target_table from H,I,J,K fields in source table
          Else 
                 insert a new row with fields X,Y,Z. H,I,J,K fields  from source table to A,B,C,P,Q,R,S in target_table

我是新手在python中使用SQL语句,我试过它,

             sql = 'select H, I, J, K from %s where X=? and Y=? and Z=?' \
                % source_table
             row = cursor.execute(sql, values).fetchone()

             sql = 'select A, B, C from %s where A=? and B=? and C=?' \
                % target_table

             tocompare_row = cursor.execute(sql, values).fetchone()

             if X == tocompare_row[0] and Y == tocompare_row[1] and Z== tocompare_row[2]:
                 sql = 'Update %s SET P=%s, Q=%s, R=%s, S=%s where A=? and B=? and C=? ' \
                   % target_table, row[0], row[1], row[2], row[3]

                 cursor.execute(sql, [X, Y, Z])

              else :
                sql = 'Insert into  %s (A, B, C, P, Q, R, S) VALUES (%s, %s, %s, %s, %s)' \
                  % target_table, X, Y, Z, row[0], row[1], row[2], row[3]
                cursor.execute(sql)

如果我做得对,请有人告诉我吗?

非常感谢!!

0 个答案:

没有答案