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";
}
?>
相关推荐
正在走向自律1 小时前
网络安全防护指南:筑牢网络安全防线(5/10)
网络·web安全·php
码哥字节3 小时前
面试提问:JVM 垃圾回收算法有哪些?CMS、G1、ParNew、Serial、Parallel 原理是什么?...
jvm·算法·面试·职场和发展
Aileen_0v04 小时前
Java面向对像编程OOP
java·jvm·windows·spring·eclipse·csdn开发云
故苏呦5 小时前
PHP升级
开发语言·php
ac-er88885 小时前
利用PHP和GD库生成随机背景图片
开发语言·php
网络安全成叔5 小时前
超详细搭建PhpStorm+PhpStudy开发环境
android·网络安全·php·phpstorm·phpstudy
龙哥·三年风水5 小时前
群控系统服务端开发模式-应用开发-邮件工厂结构封装
分布式·php·群控系统
zhlh_xt6 小时前
Java应用系统卡顿之JVM参数优化案例
java·jvm·性能优化·jvm参数优化·java应用优化
落落鱼20136 小时前
TP6 html生成ptf并加盖骑缝章
html·php
only-qi7 小时前
JVM学习《垃圾回收算法和垃圾回收器》
jvm·学习·算法