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/jihantoro.net$ 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/README.md
      create  jihantoro-cr-mysql/.travis.yml
      create  jihantoro-cr-mysql/shard.yml
      create  jihantoro-cr-mysql/src/jihantoro-cr-mysql.cr
      create  jihantoro-cr-mysql/src/jihantoro-cr-mysql/version.cr
      create  jihantoro-cr-mysql/spec/spec_helper.cr
      create  jihantoro-cr-mysql/spec/jihantoro-cr-mysql_spec.cr
Initialized empty Git repository in /home/ayam/Documents/jihantoro.net/jihantoro-cr-mysql/.git/

2. Edit your shard.yml

make sure your shard.yml look like this

name: jihantoro-cr-mysql
version: 0.1.0

authors:
  - Rubi Jihantoro 

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

targets:
  jihantoro-cr-mysql:
    main: src/jihantoro-cr-mysql.cr

crystal: 0.23.0

license: MIT

3. Installing Dependencies


ayam@laptop:~/Documents/jihantoro.net/jihantoro-cr-mysql$ shards install
Updating https://github.com/crystal-lang/crystal-db.git
Updating https://github.com/crystal-lang/crystal-mysql.git
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 = DB.open "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