簡體   English   中英

Python 插入oracle數據到sql服務器

[英]Python insert oracle data into sql server

我目前正在尋找一個 python 腳本,它將從 oracle 數據庫中提取數據並將其插入到 SQL SERVER 數據庫中

目前我已經創建了一個 python 腳本來從 oracle 數據庫中提取數據,下面是我的代碼

import csv
import cx_Oracle

# establish connection
connection = cx_Oracle.connect(
user="username", 
password="password",
dsn="servername/PROD")

# create cursor object
cursor = connection.cursor()

# query to display all the data 
cursor.execute("""SELECT *
FROM LOTTO_BI.LOTO_DRAW_RESULTS 
ORDER BY DRAW_NUM""")

# print each row in the cursor
for i in cursor:
print(i)

我的代碼中缺少的是將 oracle 數據插入 SQL SERVER 表的部分

import pyodbc
import csv
import cx_Oracle

# establish connection
connection = cx_Oracle.connect(
user="username", 
password="password",
dsn="servername/PROD")

# create cursor object
cursor = connection.cursor()

# query to display all the data 
cursor.execute("""SELECT *
FROM LOTTO_BI.LOTO_DRAW_RESULTS 
ORDER BY DRAW_NUM""")

# Fetch all rows
oracle_rows = cursor.fetchall()


# Establish a connection to the SQL Server database
sql_server_conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=sql_server_host;DATABASE=sql_server_db;UID=user;PWD=password')

# create cursor object
sql_server_cursor = sql_server_conn.cursor()

# Insert the rows into the SQL Server database
for row in oracle_rows:
    sql_server_cursor.execute('INSERT INTO sql_server_table VALUES (?, ?, ?)', row)

# Commit changes
sql_server_conn.commit()


# Close connections
oracle_cursor.close()
oracle_conn.close()
sql_server_cursor.close()
sql_server_conn.close()

我已將下面的代碼添加到您的代碼中。 這里假設 Oracle 中的表和 SQL Server 中的表具有相同的結構,具有相同的列數和數據類型。

嗯,為了簡單起見,只需使用pandas庫,它可以使用to_sql()方法從一個 sql 引擎轉換為另一個引擎。

由於我本地沒有 Oracle 數據庫,這個例子告訴你如何做同樣的事情,將 MYSQL 數據插入到 SQLite 數據庫

import pandas as pd
import sqlalchemy
import mysql.connector

# Connect to the MYSQL Database using the mysql.connector library
connection = mysql.connector.connect(
    host='localhost',
    user='root',
    password='password',
    database='storefront2')

# Create a SQLAlchemy engine for the SQLite database
engine = sqlalchemy.create_engine('sqlite:///storefront2.db')

# Read `store_product` data from the MYSQL database
df = pd.read_sql('SELECT * FROM store_product', connection)

# Write the data from the DataFrame to the SQLite database
df.to_sql('store_product', engine, if_exists='replace', index=False)

至於您, connection將是與您的Oracle數據庫的連接(您可以保持連接),而engine將是與SQLServer的連接。

編輯:為 SQLServer 創建引擎,使用:

engine = sqlalchemy.create_engine("mssql+pymssql://scott:tiger@hostname:port/dbname")

或簽SQLAlchemy documentationhttps://docs.sqlalchemy.org/en/14/core/engines.html#microsoft-sql-server

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM