我想创建DATABASE,并且在同一个数据库中想要导入数据。但是,自从没有运气以后我尝试了。
动作
public function actionRestore($id = null)
{
$list = $this->getFileList();
$file = $list[$id];
if(isset($file))
{
$transaction = Yii::$app->db->beginTransaction();
try{
$sql = 'DROP DATABASE IF EXISTS '.$this->getDbName().';CREATE DATABASE '.$this->getDbName();
$sqlFile = $this->path . basename($file);
Yii::$app->db->pdo->prepare($sql,$this->execSqlFile($sqlFile));
if(Yii::$app->db->pdo->exec())
{
$transaction->commit();
Yii::$app->session->setFlash('success', 'Backup Restored Successfully');
return $this->redirect(['index']);
}
$transaction->rollback();
}
catch(\Exception $e) {
$transaction->rollBack();
Yii::$app->session->setFlash('error', "Backup not Restored. <br>".$e->getMessage());
return $this->redirect(['index']);
}
}
}
我不确定 execSqlFile()方法:
public function execSqlFile($sqlFile)
{
$flag = false;
if (file_exists($sqlFile))
{
$sqlArray = file_get_contents($sqlFile);
$cmd = Yii::$app->db->createCommand($sqlArray);
try {
$cmd->execute();
$flag = true;
}
catch(Exception $e)
{
$flag = false;
throw new \yii\db\Exception($e->getMessage());
}
}
return $flag;
}
1)getDbName()
获取数据库名称
1)getFileList()
获取要在execSqlFile()
执行的文件。
我没有收到任何错误或成功或失败的信息 我想将两者合并为一个preparedStatement,但不知道我在这里缺少什么。
答案 0 :(得分:1)
我找到了需要使用shell_exec
的解决方案:
public function execSqlFile($sqlFile)
{
if (file_exists($sqlFile))
{
$database=array();
$db=Yii::$app->db;
$database=explode(";",$db->dsn);
$dbname=explode("=",$database['1']);
$output = shell_exec('mysql -u '.$db->username.' -p'.$db->password.' '. $dbname['1'] .'< '.$sqlFile);
}
return $output;
}
答案 1 :(得分:0)
不要直接使用PDO
对象。你放松了抽象。我只会执行两个命令:
public function actionRestore($id = null)
{
if($id !== null && $this->restoreDatabase($id)) {
Yii::$app->session->setFlash('success', 'Backup Restored Successfully');
} else {
Yii::$app->session->setFlash('error', "Backup not Restored. <br>" . $e->getMessage());
}
return $this->redirect(['index']);
}
private function restoreDatabase($id)
{
$list = $this->getFileList();
$file = $list[$id];
if (isset($file)) {
$transaction = Yii::$app->db->beginTransaction();
try {
Yii::$app->db->createCommand('DROP DATABASE IF EXISTS ' . $this->getDbName() . '; CREATE DATABASE ' . $this->getDbName())->execute();
$sqlFile = $this->path . basename($file);
$this->execSqlFile($sqlFile);
$transaction->commit();
return true;
} catch (\Exception $e) {
$transaction->rollBack();
Yii::error($e->getMessage()); //Probably throw exception?
return false;
}
}
}
private function execSqlFile($sqlFile)
{
if (!file_exists($sqlFile)) {
return false;
}
$sql = file_get_contents($sqlFile);
$command = Yii::$app->db->createCommand($sql);
try {
$command->execute();
return true;
} catch (Exception $e) {
throw new \yii\db\Exception($e->getMessage());
}
}