Laravel5.1学习笔记15 数据库1 数据库使用入门

Introduction

Laravel makes connecting with databases and running queries extremely simple across a variety of database back-ends using either raw SQL, the fluent query builder, and the Eloquent ORM. Currently, Laravel supports four database systems:

  • MySQL
  • Postgres
  • SQLite
  • SQL Server
Configuration

Laravel makes connecting with databases and running queries extremely simple. The database configuration for your application is located at config/database.php. In this file you may define all of your database connections, as well as specify which connection should be used by default. Examples for all of the supported database systems are provided in this file.

By default, Laravel‘s sample environment configuration is ready to use with Laravel Homestead, which is a convenient virtual machine for doing Laravel development on your local machine. Of course, you are free to modify this configuration as needed for your local database.

Read / Write Connections

Sometimes you may wish to use one database connection for SELECT statements, and another for INSERT, UPDATE, and DELETE statements. Laravel makes this a breeze, and the proper connections will always be used whether you are using raw queries, the query builder, or the Eloquent ORM.

To see how read / write connections should be configured, let‘s look at this example:

‘mysql‘ => [
    ‘read‘ => [
        ‘host‘ => ‘192.168.1.1‘,
    ],
    ‘write‘ => [
        ‘host‘ => ‘196.168.1.2‘
    ],
    ‘driver‘    => ‘mysql‘,
    ‘database‘  => ‘database‘,
    ‘username‘  => ‘root‘,
    ‘password‘  => ‘‘,
    ‘charset‘   => ‘utf8‘,
    ‘collation‘ => ‘utf8_unicode_ci‘,
    ‘prefix‘    => ‘‘,
],

Note that two keys have been added to the configuration array: read and write. Both of these keys have array values containing a single key: host. The rest of the database options for the read and write connections will be merged from the main mysql array.

So, we only need to place items in the read and write arrays if we wish to override the values in the main array. So, in this case, 192.168.1.1 will be used as the "read" connection, while 192.168.1.2 will be used as the "write" connection. The database credentials, prefix, character set, and all other options in the main mysql array will be shared across both connections.

Running Raw SQL Queries

Once you have configured your database connection, you may run queries using the DB facade. The DB facade provides methods for each type of query: select, update, insert, and statement.

Running A Select Query

To run a basic query, we can use the select method on the DB facade:

<?php

namespace App\Http\Controllers;

use DB;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * Show a list of all of the application‘s users.
     *
     * @return Response
     */
    public function index()
    {
        $users = DB::select(‘select * from users where active = ?‘, [1]);

        return view(‘user.index‘, [‘users‘ => $users]);
    }
}

The first argument passed to the select method is the raw SQL query, while the second argument is any parameter bindings that need to be bound to the query. Typically, these are the values of the where clause constraints. Parameter binding provides protection against SQL injection.

The select method will always return an array of results. Each result within the array will be a PHP StdClass object, allowing you to access the values of the results:

foreach ($users as $user) {
    echo $user->name;
}
Using Named Bindings

Instead of using ? to represent your parameter bindings, you may execute a query using named bindings:

$results = DB::select(‘select * from users where id = :id‘, [‘id‘ => 1]);
Running An Insert Statement

To execute an insert statement, you may use the insert method on the DB facade. Like select, this method takes the raw SQL query as its first argument, and bindings as the second argument:

DB::insert(‘insert into users (id, name) values (?, ?)‘, [1, ‘Dayle‘]);
Running An Update Statement

The update method should be used to update existing records in the database. The number of rows affected by the statement will be returned by the method:

$affected = DB::update(‘update users set votes = 100 where name = ?‘, [‘John‘]);
Running A Delete Statement

The delete method should be used to delete records from the database. Like update, the number of rows deleted will be returned:

$deleted = DB::delete(‘delete from users‘);
Running A General Statement

Some database statements should not return any value. For these types of operations, you may use the statementmethod on the DB facade:

DB::statement(‘drop table users‘);

Listening For Query Events

If you would like to receive each SQL query executed by your application, you may use the listen method. This method is useful for logging queries or debugging. You may register your query listener in a service provider:

<?php

namespace App\Providers;

use DB;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        DB::listen(function($sql, $bindings, $time) {
            //
        });
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Database Transactions

To run a set of operations within a database transaction, you may use the transaction method on the DB facade. If an exception is thrown within the transaction Closure, the transaction will automatically be rolled back. If the Closureexecutes successfully, the transaction will automatically be committed. You don‘t need to worry about manually rolling back or committing while using the transaction method:

DB::transaction(function () {
    DB::table(‘users‘)->update([‘votes‘ => 1]);

    DB::table(‘posts‘)->delete();
});
Manually Using Transactions

If you would like to begin a transaction manually and have complete control over rollbacks and commits, you may use the beginTransaction method on the DB facade:

DB::beginTransaction();

You can rollback the transaction via the rollBack method:

DB::rollBack();

Lastly, you can commit a transaction via the commit method:

DB::commit();

Note: Using the DB facade‘s transaction methods also controls transactions for the query builder andEloquent ORM.

Using Multiple Database Connections

When using multiple connections, you may access each connection via the connection method on the DB facade. The name passed to the connection method should correspond to one of the connections listed in yourconfig/database.php configuration file:

$users = DB::connection(‘foo‘)->select(...);

You may also access the raw, underlying PDO instance using the getPdo method on a connection instance:

$pdo = DB::connection()->getPdo();
时间: 2024-10-05 04:56:06

Laravel5.1学习笔记15 数据库1 数据库使用入门的相关文章

[Spring Data MongoDB]学习笔记--建立数据库的连接

1. 有了上一篇的Mongo后,连接数据库我们还需要更多的信息,比如数据库名字,用户名和密码等. 我们可以继续来配置MongoDbFactory的实例. public interface MongoDbFactory { DB getDb() throws DataAccessException; DB getDb(String dbName) throws DataAccessException; } 然后我们可以继续用MongoDbFactory来创建MongoTemplate的实例. pu

sqlite学习笔记2:创建数据库

在上一次笔记中最后生成了一个sqlite可执行文件,cd到sqlite所在的目录下面执行: sqlite3 MyDataBase.db 就会创建了一个名叫MyDataBase.db的数据库,在当前路径下面就会生成一个叫MyDataBase.db的文件 #切记不是先运行sqlite3,然后再上述命令,而是在终端直接输入上述命令,否则会报错:Error: near "sqlite3": syntax error 然后运行命令: .databases 可以查看刚刚创建的数据库,退出数据库命令

Sharepoint2013商务智能学习笔记之部署AdventureWorksDW2012数据库(三)

AdventureWorksDW2012是sql server2012的样本数据库,后面做商务智能Demo会用到,所以需要下载并安装到sql server2012上,下载地址 第一步,下载数据库 第二步,进入Sql server management studio,点击数据库右键附加下载好的 AdventureWorksDW2012数据库,附加时候记得删除数据库日志. 第三步,在做商务智能demo,连接多维数据源的时候需要用到微软Analysis Services Tutorial SQL Se

sqlite学习笔记3:附加数据库和分离数据库

在前面说了如果创建一个数据库,接下来我们需要操作数据库: 但是sqlite3命令一次只能操作一个数据库,如果当前路径下有多个数据库该怎么办呢?这就需要用到附加数据库. 一  关联数据库 附加数据库实际上就是告诉sqlite3,你写的SQL语句是操作的哪一个数据库.具体如何操作呢? 基本语法如下: ATTACH DATABASE 'DatabaseName' As 'Alias-Name'; *sqlite3中的语句都需要以分好结束 使用上面的命名,如果数据库存在,将会被关联到'Alias-Nam

学习笔记(十三)——数据库备份还原的知识点与注意事项

学习笔记(十三)——数据库备份还原的知识点与注意事项 一.备份还原基本概念 1.  完整备份:完整备份因为需要备份的数据量大,所以需要在空闲时间进行,并且定期进行. 2.  日志备份:日志备份的数据量小,备份时间为上一次备份到本次本分期间的数据,每天都可以进行备份,或者每小时都可以进行备份,据所需备份. 3.  增量备份(差异备份):只备份修改过的数据,与每小时进行的日志备份配合使用,效率更高. 二.备份设备 1.          在进行备份数据的保存时,需要输入的文件路径很长,并且每次都要输

Perl语言学习笔记 15 智能匹配与give-when结构

1.智能匹配操作符 替代绑定操作符: 在哈希中查找某一个键: 比较两个数组是否完全相同: 查找列表中是否存在某个元素: 智能匹配操作符与顺序无关,~~ 左右元素可以互换 2.智能操作符优先级 3.given语句 相当于c语言的switch语句 4.given可以测试多个条件,在default前用break,否则会导致default一直执行 5.笨拙匹配(正则表达式方式) 6.多个项目的when匹配 可以在语句中间加上其他语句: Perl语言学习笔记 15 智能匹配与give-when结构,布布扣

Swift学习笔记(15)--下标脚本(Subscripts)

下标脚本可以定义在类(Class).结构体(structure)和枚举(enumeration)这些目标中,使用中类似数组或者字典的用法 1.定义 定义下标脚本使用subscript关键字,语法: subscript(index: Int) -> Int { get { // 返回与入参匹配的Int类型的值 } set(newValue) { // 执行赋值操作 } } 注:newValue的类型必须和下标脚本定义的返回类型相同.与计算型属性相同的是set的入参声明newValue就算不写,在s

python基础教程_学习笔记15:标准库:一些最爱——fileinput

标准库:一些最爱 fileinput 重要的函数 函数 描述 input([files[,inplace[,backup]]) 便于遍历多个输入流中的行 filename() 返回当前文件的名称 lineno() 返回当前(累计)的名称 filelineno() 返回当前文件的行数 isfirstline() 检查当前行是否是文件的第一行 isstdin() 检查最后一行是否来自sys.stdin nextfile() 关闭当前文件,移动到下一个文件 close() 关闭序列 fileinput

springmvc学习笔记(15)-数据回显

springmvc学习笔记(15)-数据回显 springmvc学习笔记15-数据回显 pojo数据回显方法 简单类型数据回显 本文介绍springmvc中数据回显的几种实现方法 数据回显:提交后,如果出现错误,将刚才提交的数据回显到刚才的提交页面. pojo数据回显方法 1.springmvc默认对pojo数据进行回显. pojo数据传入controller方法后,springmvc自动将pojo数据放到request域,key等于pojo类型(首字母小写) 使用@ModelAttribute