daveaztig14

daveaztig14

How to connect simple elxiir app to MySQL database and execute query?

Hi,

I have built a simple elxiir app which receives request like:

curl "http://localhost:8085/pass" -H Content-Type: application/json; charset=utf-8’ -d '{"ticket": 1, "ver": "1", "os": "1"}'

and the output is:

ticket: 1, ver: 0.0.1.0_develop, os: ios

SQL Query = select * from database where ticket= 1 AND ver= 1 AND os= 1

(for the process or steps on how i did it please refer to How to use curl as input in elixir script?)

Anyway, I have a MySQL in remote host (sample ip: 10.10.11.11), a database named fortesting and a table named testingone.

My question is how connect my elixir app to my MySQL database in remote host (ip: 10.10.11.11)? and run the query select * from fortesting where ticket= 1 AND ver= 1 AND os= 1? using for example simple_server.exs and not the interactive elixir?

I’ve tried this: https://www.amberbit.com/blog/2018/6/12/executing_raw_sql_queries_in_elixir/ but did not work for me.

Any ideas, suggestions, links and help are welcome. Thank you.

Most Liked

NobbZ

NobbZ

What is the exact error you see? What behaviour did you observe, which did you expect?

stefanluptak

stefanluptak

Since you’re using MySQL, you probably want to use MyXQL.

GitHub: https://github.com/elixir-ecto/myxql
Docs: https://hexdocs.pm/myxql/readme.html

joaoevangelista

joaoevangelista

:wave:
It is possible to use raw drivers? Yes.
Suppose you want to use on a simple, not phoenix project
creating a project using mix new my_app --sup will create the folders and the implementation of Application (the main entry point) which starts the supervision tree.

defmodule MyApp.Application do
  # See https://hexdocs.pm/elixir/Application.html
  # for more information on OTP Applications
  @moduledoc false

  use Application

  def start(_type, _args) do
    # List all child processes to be supervised
    children = [
      # Starts a worker by calling: MyApp.Worker.start_link(arg)
      # {MyApp.Worker, arg}
    ]

    # See https://hexdocs.pm/elixir/Supervisor.html
    # for other strategies and supported options
    opts = [strategy: :one_for_one, name: MyApp.Supervisor]
    Supervisor.start_link(children, opts)
  end
end

Now the driver is just a “Worker” and we can start under the supervisor.

  • Add {:myxql, "~> 0.2.0"} to your dependencies and run mix deps.get, this is a new driver made for newer versions of mysql
  • Supports MySQL 5.7.10+, 8.0, and MariaDB 10.3
  • Now under the MyApp.Application.start/2 function we have the children list, there we will add the initialization for the driver.
children = [
  {MyXQL, hostname: "10.10.11.11", username: "username", password: "password", database: "fortesting", name: :mydb}
]

Note that we add a key name to the options with value :mydb that is our identifier to use the same driver process in the application without the need to start/stop when a request comes.

Now on your controller action or any where you need, even on iex -S mix :

{:ok, result} = MyXQL.query(:mydb, "select * from database where ticket = ? and ver = ? and os = ?", [ticket_param, ver_param, os_param])

Performing the query with ? on the string allows the driver do the sanatization, preventing SQL Injection.

And thats it. For more infor on what you get from MyXQL.query/3 you can see the docs and the github repo

wmnnd

wmnnd

It seems like you’re just getting started with Elixir, so you might want to check out Ecto which is used by most people in the Elixir community for working with SQL databases.

Take a look at the Getting Started guide:
https://hexdocs.pm/ecto/getting-started.html

NobbZ

NobbZ

If you use ecto, then you will need a Repo, as the Repo is your wrapper around the connection pooling.

Of course you can also use postgrex (or any other driver) to directly do the low level dirty work to talk to your database…

Where Next?

Popular in Questions Top

Tee
can someone please explain to me how Enum.reduce works with maps
New
LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
logicmason
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New

Other popular topics Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New

We're in Beta

About us Mission Statement