Symfony3.x.x通过命令行操作数据库
-
配置app/config/parameters.yml
parameters: database_host: 127.0.0.1 database_port: 3306 database_name: test database_user: root database_password: null mailer_transport: smtp mailer_host: 127.0.0.1 mailer_user: 127001@qq.com mailer_password: null secret: 8ab34c9326ac123b2dea2fab13e4ab
-
配置app/config/config.yml
doctrine: dbal: driver: pdo_mysql host: "%database_host%" port: "%database_port%" dbname: "%database_name%" user: "%database_user%" password: "%database_password%" charset: UTF8
- 创建TestBundle
- 在TestBundle目录(文件夹)下,新建Command目录(文件夹)
-
在Command目录新建TestCommand.php,代码如下:
<?php //src/TestBundle/Command/TestCommand.php namespace TestBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; class TestCommand extends ContainerAwareCommand { protected function configure() { $this->setName('database:run') ->setDescription('Run an action.') ->addArgument('name', InputArgument::OPTIONAL, 'Chouse an action to run.') ->addOption('show', null, InputOption::VALUE_NONE, 'Show result.'); } protected function execute(InputInterface $input, OutputInterface $output) { $name = $input->getArgument('name'); if ($name == 'action1'){ $text = $this->myAction1(); }elseif($name == 'action2') { $text = $this->myAction2(); }elseif($name == 'action3') { $text = $this->myAction3(); }else { $text = 'Error[101]:Cmd error.'; } if (!$input->getOption('show')){ $text = NULL; } $output->writeln($text); } protected function myAction1() { //这句非常重要 $conn = $this->getContainer()->get('database_connection'); $bool= $conn->exec( //这里的SQL语句自己定义 'INSERT INTO 表名(id,live,age)VALUE(1,\'dog\',20)' ); $conn = null; if($bool) $str = "Action1 has been executed."; else $str = "Not insert data."; return $str; } protected function myAction2() { if(true) $str = "Action2 has been executed."; else $str = "Did not perform any action!"; return $str; } protected function myAction3() { if(true) $str = "Action3 has been executed."; else $str = "Did not perform any action!"; return $str; } }
-
尝试在命令行执行:
Php bin/console --show database:run action1
(1)如果返回:Action1 has been executed.说明操作成功;
(2)如果返回:Not insert data.就要检查自己的sql语句是否有误
- 如果命令行中不输入:‘--show’表示不显示执行结果。
- action1 也可以是action2、action3。
意义
Symfony通过命令行操作数据库的意义在于
- 可以将方法不和URL进行绑定,实现方法的运行,有效防止sql注入;
- 由于命令定义的灵活性,非内部人员不知道你的命令行的格式,也不知道其实现何种操作。