从 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()

完结!

相关推荐
2601_9679801111 分钟前
python pytest如何编写测试
python·测试用例·pytest·函数·assert
泯泷12 分钟前
别再“裸聊”大模型了!你家的 AI 为什么总胡说八道?根子在 RAG
人工智能·算法·架构
玖米GEO运营王总监20 分钟前
成都AI数字人视频怎么批量生产?流程与合规标注
大数据·人工智能·音视频
f6m274dww2cmd1 小时前
拆一个类目第一的20个曝光词:43% 的搜索量来自第二页
人工智能
2601_967980111 小时前
Python中heapq模块的各种用法实例
数据结构·python·算法·应用实例·heapq模块
大胖爱学习_MJ1 小时前
超越向量检索:用 Spring Boot + Neo4j 手搓 GraphRAG 知识图谱记忆
java·后端·python
RobinDevNotes1 小时前
24GB Mac 做数字人:声音放本地,画面租云端
人工智能·python·macos·开发工具
龙腾AI白云2 小时前
数字孪生与计算机视觉:让机器看懂现场
大数据·数据库·机器学习·知识图谱·pygame
user4465117917912 小时前
Agent 也能「过安检」:AgentScope 权限系统设计拆解
人工智能
烟小栀2 小时前
Windows下的深度学习环境配置参考及配置教程
人工智能