phoenix 使用activerecord模式框架ecto 访问数据库

时间:2022-01-08 00:07:48
备注:
   需要先安装mysql 以及phoenix 框架,测试使用的是docker 进行安装,具可以参考代码
 
 1. 创建项目
mix phx.new first --database mysql
  2. 修改数据库链接
config/dev.exs

config :first, First.Repo,
adapter: Ecto.Adapters.MySQL,
username: "root",
password: "dalongrong",
database: "demoapp",
hostname: "localhost",
pool_size: 10,
port: 3307
3.  数据库准备
./dockerrun.sh

备注: 使用docker

#!/bin/bash
docker run -d --name mysql-server57 -p 3307:3306 -e MYSQL_ROOT_PASSWORD=dalongrong -e MYSQL_ROOT_HOST=% mysql/mysql-server:5.7
 
4.  使用ecto 创建数据库访问
a. 使用脚手架生成代码

mix phx.gen.schema User users name:string email:string \
bio:string number_of_pets:integer b. 生成表结构 mix ecto.migrate
 
5. 数据访问处理(比较简单)
使用命令行

iex -S mix

alias First.{Repo, User}

Repo.insert(%User{email: "user1@example.com"})

[debug] QUERY OK db=2.9ms
INSERT INTO `users` (`email`,`inserted_at`,`updated_at`) VALUES (?,?,?) ["user1@example.com", {{2018, 4, 19}, {2, 50, 7, 547207}}, {{2018, 4, 19}, {2, 50, 7, 549585}}]
{:ok,
%First.User{
__meta__: #Ecto.Schema.Metadata<:loaded, "users">,
bio: nil,
email: "user1@example.com",
id: 1,
inserted_at: ~N[2018-04-19 02:50:07.547207],
name: nil,
number_of_pets: nil,
updated_at: ~N[2018-04-19 02:50:07.549585]
}} Repo.all(User)
[debug] QUERY OK source="users" db=3.3ms
SELECT u0.`id`, u0.`bio`, u0.`email`, u0.`name`, u0.`number_of_pets`, u0.`inserted_at`, u0.`updated_at` FROM `users` AS u0 []
[
%First.User{
__meta__: #Ecto.Schema.Metadata<:loaded, "users">,
bio: nil,
email: "user1@example.com",
id: 1,
inserted_at: ~N[2018-04-19 02:50:08.000000],
name: nil,
number_of_pets: nil,
updated_at: ~N[2018-04-19 02:50:08.000000]
}
]
6. 参考资料
https://hexdocs.pm/phoenix/ecto.html#content
https://github.com/rongfengliang/phoenix-ecto-demo