PHP将指定文件夹下多csv文件[即多表]导入到sqlite单文件

支持多表,中文字段,csv文件utf-8编码 逗号分隔,第一行字段以后一行一条内容

php 复制代码
<?php

class CsvToSqlite {
    private $db;
    private $csvDir;
    private $sqliteFile;
    public function __construct($csvDir, $sqliteFile) {
        $this->csvDir = rtrim($csvDir, '/');
        $this->sqliteFile = $sqliteFile;
        try {
            $this->db = new PDO("sqlite:{$this->sqliteFile}");
            $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $e) {
            die("数据库连接失败: " . $e->getMessage());
        }
    }
    public function convert() {
        $csvFiles = glob($this->csvDir . '/*.csv');        
        foreach ($csvFiles as $csvFile) {
            $this->processCsvFile($csvFile);
        }        
        echo "所有CSV文件处理完成!\n";
    }
    private function processCsvFile($csvFile) {
        $tableName = pathinfo($csvFile, PATHINFO_FILENAME);
        echo "正在处理文件: {$csvFile}\n";        
        try {
            $handle = fopen($csvFile, 'r');
            if ($handle === false) throw new Exception("无法打开文件: {$csvFile}");
            $headers = fgetcsv($handle);
            if ($headers === false) throw new Exception("CSV文件为空: {$csvFile}");
            $this->createTable($tableName, $headers);
            $placeholders = str_repeat('?,', count($headers) - 1) . '?';
            $sql = "INSERT INTO {$tableName} VALUES ($placeholders)";
            $stmt = $this->db->prepare($sql);
            $this->db->beginTransaction();
            while (($row = fgetcsv($handle)) !== false) {
                if (count($row) === count($headers)) {
                    try {
                        $stmt->execute($row);
                    } catch (PDOException $e) {
                        echo "插入数据失败: " . $e->getMessage() . "\n";
                        continue;
                    }
                }
            }
            $this->db->commit();            
            fclose($handle);
            echo "表 {$tableName} 创建并导入完成\n";            
        } catch (Exception $e) {
            if ($this->db->inTransaction()) {
                $this->db->rollBack();
            }
            echo "处理文件 {$csvFile} 时出错: " . $e->getMessage() . "\n";
        }
    }
    private function createTable($tableName, $headers) {
        $tableName = $this->sanitizeIdentifier($tableName);
        $columns = array_map([$this, 'sanitizeIdentifier'], $headers);
        $columnDefs = array_map(function($col) {
            return "{$col} TEXT";
        }, $columns);        
        $sql = "CREATE TABLE IF NOT EXISTS {$tableName} (" . 
               implode(', ', $columnDefs) . ")";        
        try {
            $this->db->exec($sql);
            $this->db->exec("DELETE FROM {$tableName}");
        } catch (PDOException $e) {
            throw new Exception("创建表失败: $sql@" . $e->getMessage());
        }
    }
    private function sanitizeIdentifier($identifier) {
        $safe = preg_replace('/[^\w\x{4e00}-\x{9fa5}]+/u', '_', $identifier);
        if (is_numeric($safe[0])) { $safe = 'col_' . $safe;}
        return Trim($safe,"_");
    }
    public function getTableRowCount($tableName) {
        $tableName = $this->sanitizeIdentifier($tableName);
        $stmt = $this->db->query("SELECT COUNT(*) FROM {$tableName}");
        return $stmt->fetchColumn();
    }
    public function __destruct() {
        $this->db = null;
    }
}

// 使用示例
try {
    $csvDir = './csv_files';
    $sqliteFile = './database.sqlite';    
    $converter = new CsvToSqlite($csvDir, $sqliteFile);    
    $converter->convert();    
} catch (Exception $e) {
    echo "发生错误: " . $e->getMessage() . "\n";
}
?>
相关推荐
程序猿chen19 分钟前
《JVM考古现场(十六):太初奇点——从普朗克常量到宇宙弦的编译风暴》
jvm·git·后端·程序人生·金融·java-ee·量子计算
tjsoft40 分钟前
实操日志之Windows Server2008R2 IIS7 配置Php7.4.3
windows·iis·php·2008·7.4.3
stark张宇7 小时前
三步接入DeepSeek智能对话API:PHP代码实现与响应解析
后端·php·deepseek
Excuse_lighttime7 小时前
JAVA阻塞队列
java·开发语言·jvm
熙客8 小时前
JVM监控
jvm
w23617346019 小时前
Linux常用基础命令应用
linux·服务器·php
欲儿10 小时前
在线记事本——支持Markdown
前端·javascript·程序人生·sqlite·php·轻量级在线记事本
我是唐青枫11 小时前
php8 命名参数使用教程
php
Thanwind12 小时前
关于JVM和OS中的指令重排以及JIT优化
java·jvm·jmm
快来卷java15 小时前
JVM虚拟机篇(三):JVM运行时数据区与方法区详解
java·jvm·mysql