Joining Data Frame & SQL Server table directly and update table

37 Views Asked by At

I am new to Python, looking for options on direct join (Just like sql join b/w tables) between Data Frame and SQL Server table and Insert/update table(s).Is there way to join and Insert/update without using Temp table or Cursor.

Reason : In actual scenario, i have millions of rows between the tables DF & SQL Server Tables.My understanding is .....using temp table or cursor is expensive process. So looking for options.

This is how the Dataframe looks like:

            name      author     count
         0  a         b          10
         1  c         d          5
         2  e         g          2

I need to join it with a SQL Server table that looks as below: TABLE: Books

          title   author    url         Count
          a       b         a.com.      Null
          b       z         b.com.      Null
          e       g         c.com.      Null

I want to join df & Books on df.name & Books.title and insert missing rows from df into Books and update Count column from df.

  Insert into Books (title  ,author  ,url ,Count)
  select name, author, count 
  from df left join Books on df.name =  Books.title
  where Books.title is null 

 update Books
 set Count = df.Count
 from df Inner join Books on df.name =  Books.title

Can anyone guide me how to achieve this. Thanks!

Result :

    title   author    url         Count
    a       b            a.com.  10
    b       z            b.com.  5
    e       g            c.com.  2
    c       d            Null    5
0

There are 0 best solutions below