LoginSignup
0
1

More than 3 years have passed since last update.

SalesforceからAzure DBへの引っ越しをPythonで行う

Posted at

Screen Shot 2021-01-04 at 13.59.32.png

概要

あえてSFDCをDataframeにしてAzure DBに入れるのをPythonでやります。

SFDCのdf化

こちらの記事をご覧ください。
https://qiita.com/tetsuyaimagawa/items/26e3ceeb56e92e40d0d9#salesforce%E3%83%87%E3%83%BC%E3%82%BF%E3%82%92dataframe%E3%81%A7%E6%8A%9C%E3%81%84%E3%81%A6%E3%81%8F%E3%82%8B
👇のような感じです。

import cdata.salesforce as mod
import pandas as pd
from sqlalchemy import create_engine

engine = create_engine("salesforce:///?User=a@b.com;Password=xxx;SecurityToken=yyy;")
df = pd.read_sql("SELECT * FROM Object1;", engine)

Azure DBにテーブルを作る

import pyodbc
server = 'aaa.database.windows.net'
database = 'bbb'
username = 'xxx'
password = 'yyy'   
driver= '{ODBC Driver 17 for SQL Server}'

with pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password) as conn:
    with conn.cursor() as cursor:
        cursor.execute("
         CREATE TABLE [dbo].[Object1](
         [id] [int] IDENTITY(1,1) NOT NULL,
         [name] [nchar](128) NULL,
         [str] [nchar](64) NULL,
         [num] [decimal](18, 0) NULL
         ) ON [PRIMARY]
         ")

公式はwithで書かれていましたが、👇のような感じで大丈夫です。

conn = pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = conn.cursor()

#作業

conn.commit()
cursor.close()

dfをAzure DBにINSETする

SFDCから落としたdfがものすごい簡易化して👇のようなものだとします。

col1 col2 col3
1 name1 str1 1
2 name2 str2 2
for index, row in df.iterrows():
    cursor.execute("INSERT INTO [dbo].[Object1] (name, str, num) values(?,?,?)", row.col1, 
    row.col2, row.col3)

これでテーブル一つ引っ越し完了です。

Azure DBのデータをdfで取得する

確認も兼ねて、INSETしたものをSELECTしてdfにします。

query = "SELECT * FROM [dbo].[Object1]"
df = pd.read_sql(query, conn)

まとめ

csvを落とした方が速いことがわかりました。
(私のような)SQL Server未経験者は文法に発狂するので、やめておいたほうがよいと思いました。

0
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1