81 行
2.6 KiB
PHP
81 行
2.6 KiB
PHP
<?php
|
|
// 数据库配置
|
|
$host = '127.0.0.1';
|
|
$dbname = 'mss_nahaichuan_c';
|
|
$username = 'mss_nahaichuan_c';
|
|
$password = 'MyNmyAaRj9yWKPKH';
|
|
|
|
try {
|
|
// 连接数据库
|
|
$pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
|
|
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
|
|
|
echo "数据库连接成功!\n";
|
|
|
|
// 读取SQL文件
|
|
$sqlFile = 'import_alcohol_goods_data_fixed.sql';
|
|
if (!file_exists($sqlFile)) {
|
|
throw new Exception("SQL文件不存在: $sqlFile");
|
|
}
|
|
|
|
$sql = file_get_contents($sqlFile);
|
|
|
|
// 移除注释行
|
|
$lines = explode("\n", $sql);
|
|
$cleanedLines = array_filter($lines, function($line) {
|
|
$line = trim($line);
|
|
return !empty($line) && substr($line, 0, 2) !== '--';
|
|
});
|
|
$cleanedSql = implode("\n", $cleanedLines);
|
|
|
|
// 分割SQL语句
|
|
$statements = array_filter(explode(';', $cleanedSql), function($stmt) {
|
|
return !empty(trim($stmt));
|
|
});
|
|
|
|
$successCount = 0;
|
|
$errorCount = 0;
|
|
|
|
foreach ($statements as $statement) {
|
|
$statement = trim($statement);
|
|
if (empty($statement)) {
|
|
continue;
|
|
}
|
|
|
|
echo "准备执行: " . substr($statement, 0, 50) . "...\n";
|
|
|
|
try {
|
|
if (stripos($statement, 'SELECT') === 0) {
|
|
// 对于SELECT语句,使用query并获取结果
|
|
$result = $pdo->query($statement);
|
|
if ($result) {
|
|
$data = $result->fetchAll(PDO::FETCH_ASSOC);
|
|
$result->closeCursor();
|
|
echo "查询成功,返回 " . count($data) . " 行数据\n";
|
|
if (!empty($data)) {
|
|
foreach ($data as $row) {
|
|
echo implode(' | ', $row) . "\n";
|
|
}
|
|
}
|
|
}
|
|
} else {
|
|
// 对于INSERT、UPDATE、DELETE等语句,使用exec
|
|
$affectedRows = $pdo->exec($statement);
|
|
echo "执行成功,影响 $affectedRows 行: " . substr($statement, 0, 50) . "...\n";
|
|
}
|
|
$successCount++;
|
|
} catch (PDOException $e) {
|
|
$errorCount++;
|
|
echo "执行失败: " . $e->getMessage() . "\n";
|
|
echo "SQL: " . substr($statement, 0, 100) . "...\n";
|
|
}
|
|
}
|
|
|
|
echo "\n导入完成!\n";
|
|
echo "成功执行: $successCount 条语句\n";
|
|
echo "执行失败: $errorCount 条语句\n";
|
|
|
|
} catch (Exception $e) {
|
|
echo "错误: " . $e->getMessage() . "\n";
|
|
}
|
|
?>
|