Ruby mysql2 gem does not return the primary key of the last inserted row if the table runs on auto increment primary key. To get the primary key you’ll need…


Table structure

Installation.

go get -u github.com/go-sql-driver/mysql

Connection string. I recommend using utf8mb4 else you will not be able to save emoji characters.

func my_db() (db *sql.DB) {
username := "root"
password := "password"
hostname := "db.mysql.com"
database := "demo"
charset := "charset=utf8mb4"
collation := "collation=utf8mb4_general_ci"
db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:3306)/%s?%s&%s",username,password,hostname,database,charset,collation))
check(err)
return db
}

Create.

func create(db *sql.DB, name, address, phone string) {
sql, e := db.Prepare("INSERT INTO contacts(name, address, phone) VALUES (?, ?, ?)")
check(e)

res, e := sql.Exec(name, address, phone)
check(e)

id, e := res.LastInsertId()
check(e)

log.Println("Created. ID=", id)
}

The prepare statement uses DB resources to escape the…


A continuation from my previous Sending Personalized SMS article. Lets imagine telco allows you to send as many messages as you can without limits and you have 100,000 messages to send to all your customers.

If you can only send 1 message per second, it will take almost 28 hours to complete. What if you run it multi threaded with a pool size of 10? That will shorten it down to almost 3 hours to complete the same task.

Say you have the name list of the 100,000 customers in “list.txt”.

+6598765432|Person1
.
.
.
.
.
+6587654321|Person100000

Ruby codes…


I have a sample table created in MySQL.

I have 3 functions
1. Connect to MySQL
2. Get all contacts
3. Insert contact

In my example, I am inserting 2 contacts and later retrieve the entire table of contacts.

Kevin FOO

A software engineer, a rock climbing, diving & inline skating enthusiast, a husband, a father.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store