数据库操作之-DB facade
- 新建数据表与连接数据库
- 使用DB facade实现CURD
创建数据表
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL COMMENT '姓名',
`age` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '年龄',
`sex` tinyint(3) unsigned NOT NULL DEFAULT '10' COMMENT '性别',
`created_at` int(11) NOT NULL DEFAULT '0' COMMENT '新增时间',
`update_at` int(11) NOT NULL DEFAULT '0' COMMENT '修改时间',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1001 DEFAULT CHARSET=utf8;
连接数据库
数据库配置文件路径laravel\config\database.php
//默认选择数据库
'default' => env('DB_CONNECTION', 'mysql'),
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],
更改数据库配置文件
env对应文件路径laravel\ .env
DB_HOST=localhost
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=root
- 使用DB facade实现CURD
- 新建StudentController.php控制器,代码如下
文件所在位置laravel\app\Http\Controllers\StudentController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
class StudentController extends Controller
{
public function test1()
{
$students = DB::select('select * from student');
var_dump($students);
}
}
配置路由,代码如下
文件所在位置laravel\app\Http\routes.php
Route::get('test1',['uses'=>'StudentController@test1']);
浏览器地址栏 http://localhost:8090/laravel/public/test1
页面输出:array(0) { }
说明数据库连接成功。
网友评论