Crystal Mysql From Scratch

2 minute read

The database is one of the most important things in the formation of a software, and to create a dynamic software, usually in need of a database, and one of the sql database is MySQL, here is how to integrate crystals with mysql.

make sure you have installed crystal on your machine

1. Init Your App

init your app, because we will make it from scratch

ayam@laptop:~/Documents/$ crystal init app jihantoro-cr-mysql
      create  jihantoro-cr-mysql/.gitignore
      create  jihantoro-cr-mysql/.editorconfig
      create  jihantoro-cr-mysql/LICENSE
      create  jihantoro-cr-mysql/
      create  jihantoro-cr-mysql/.travis.yml
      create  jihantoro-cr-mysql/shard.yml
      create  jihantoro-cr-mysql/src/
      create  jihantoro-cr-mysql/src/jihantoro-cr-mysql/
      create  jihantoro-cr-mysql/spec/
      create  jihantoro-cr-mysql/spec/
Initialized empty Git repository in /home/ayam/Documents/

2. Edit your shard.yml

make sure your shard.yml look like this

name: jihantoro-cr-mysql
version: 0.1.0

  - Rubi Jihantoro 

    github: crystal-lang/crystal-db
    github: crystal-lang/crystal-mysql

    main: src/

crystal: 0.23.0

license: MIT

3. Installing Dependencies

ayam@laptop:~/Documents/$ shards install
Installing db (0.4.2)
Installing mysql (0.3.2)

4. Create MySQL Database

Make sure you have a database named jihantoro_crmysql, and inside that database have friend table with one column, named name.

5. Let's Coding

require "./jihantoro-cr-mysql/*"
require "db"
require "mysql"

db = "mysql://username:password@localhost:3306/jihantoro_crmysql" #connect to your mysql

friend = "Rouf"

puts "inserting data..."
db.exec "insert into friend (name) values (?)", friend # insert (Create) method

puts "reading data..."
myfriend = db.query_one "select name from friend limit 1", as:{String} # read (Read) method
puts "Hi " + myfriend

puts "updating data..."
newfriend = "Alficha"
db.exec "update friend set name=? where name=?", newfriend, myfriend # update (Update) method

puts "deleting data..."
db.exec "delete from friend where name=?", newfriend

puts "Done"

db.close # close the db
conclusion I hope you can understand with this article and can directly practice it, and for crystal-mysql, there is still a type of mysql data that has not been fully supported, thank and happy coding
Github Repo for this tutorial

Leave a Comment