从 sqlite 迁移到 Oracle 数据库

从 sqlite 迁移到 Oracle 数据库

  • [0. 引言](#0. 引言)
  • [1. 代码](#1. 代码)

0. 引言

今天发现一个有意思的竞赛,竞赛中使用了 sqlite 数据库。

由于个人更习惯 Oracle 数据库,所以将 sqlite 数据库迁移到了 Oracle 数据库。

此文章记录一下迁移时使用的 Python 代码。

1. 代码

import os
import sqlite3

import oracledb
from dotenv import find_dotenv, load_dotenv

_ = load_dotenv(find_dotenv())

# 连接SQLite数据库
sqlite_conn = sqlite3.connect('./dataset/博金杯比赛数据.db')
sqlite_cursor = sqlite_conn.cursor()

# 连接Oracle数据库
oracle_conn = oracledb.connect(user="username", password="password", dsn="host:port/service_name")
oracle_cursor = oracle_conn.cursor()

# 获取SQLite数据库中的表名
sqlite_cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = sqlite_cursor.fetchall()


def map_sqlite_type_to_oracle(sqlite_type):
    # 根据需要映射SQLite数据类型到Oracle数据类型
    # 这是一个更详尽的映射示例
    mapping = {
        'INTEGER': 'NUMBER(10)',
        'TEXT': 'VARCHAR2(255)',
        'REAL': 'FLOAT',
        'BLOB': 'BLOB',
        'NUMERIC': 'NUMBER'
    }
    return mapping.get(sqlite_type, 'VARCHAR2(255)')  # 默认类型为 VARCHAR2(255)


# 迭代每个表
for table in tables:
    table_name = table[0]
    print(f"Migrating table: {table_name}")

    # 获取表结构
    sqlite_cursor.execute(f"PRAGMA table_info({table_name});")
    columns = sqlite_cursor.fetchall()

    # 构建并执行Oracle表的创建语句
    column_defs = ', '.join(f"\"{column[1]}\" {map_sqlite_type_to_oracle(column[2])}" for column in columns)
    create_table_query = f"CREATE TABLE {table_name} ({column_defs})"
    print(f"{create_table_query=}")
    oracle_cursor.execute(create_table_query)
    # 测试时想Drop掉Table时使用
    # oracle_cursor.execute(f"DROP TABLE {table_name}")

    # 准备批量插入语句
    col_placeholders = ', '.join([':' + str(i + 1) for i in range(len(columns))])
    insert_query = f"INSERT INTO {table_name} VALUES ({col_placeholders})"

    # 迁移数据
    sqlite_cursor.execute(f"SELECT * FROM {table_name};")
    rows = sqlite_cursor.fetchall()
    oracle_cursor.executemany(insert_query, rows)
    oracle_conn.commit()

sqlite_conn.close()
oracle_conn.close()

完结!

相关推荐
掘根6 分钟前
【MySQL】Ubuntu环境下MySQL的安装与卸载
数据库·mysql·centos
sp_fyf_202410 分钟前
[大语言模型-论文精读] 更大且更可指导的语言模型变得不那么可靠
人工智能·深度学习·神经网络·搜索引擎·语言模型·自然语言处理
小蜗笔记37 分钟前
在Python中实现多目标优化问题(7)模拟退火算法的调用
开发语言·python·模拟退火算法
TANGLONG22241 分钟前
【C语言】数据在内存中的存储(万字解析)
java·c语言·c++·python·考研·面试·蓝桥杯
肖遥Janic41 分钟前
Stable Diffusion绘画 | 插件-Deforum:商业LOGO广告视频
人工智能·ai·ai作画·stable diffusion
知识分享小能手1 小时前
mysql学习教程,从入门到精通,SQL 修改表(ALTER TABLE 语句)(29)
大数据·开发语言·数据库·sql·学习·mysql·数据分析
魏大橙1 小时前
Fastjson反序列化
开发语言·python
暮毅1 小时前
Django对接支付宝沙箱环境(2024年9月新测有效)
数据库·django
fat house cat_1 小时前
mysql-索引笔记
数据库·mysql