GoLang : Getting started with CockroachDB and Go Language
From last few months I have been working with CockroachDB. And after diving deeper into the philosophy of cockroach I started loving it. Reason for choosing CockroachDB are:
- Open Source
- JSON Support
- High Availability
- Strongly Consistent Replication
- Ease of use
This tutorial will cover below topics:
- Installing & Running CockroachDB
- Creating Database and Table in CockroachDB
- Installing CockroachDB Go pq library
- Connection to DB
- SQL Statement
- Full Source Code
1. Installing & Running CockroachDB
I am using MAC, so I would be showing the steps for mac for other OS you can use below URL to install CockroachDB.
brew install cockroach
Once the CockroachDB has been installed its time to start CockroachDB, Here I would be using single node server for ease of use.
Command to start CockroachDB with in a insecure mode
cockroach start --insecure
You can follow the below link to start the CockroachDB on your OS.
Once cockroach start successfully you can see following message printed on your console.
If you see the following message.
Congratulations!!! You have successfully installed and started CockroachDB.
2. Creating Database and Table in CockroachDB
We would be creating a simple database called “company_db” with table “tbl_employee”
You can now connect to CockroachDB SQL Client in a insecure mode using below command to execute the SQL statement.
cockroach sql --insecure
To create Database and to set database for current session use below SQL statement
create database company_db;
set database = company_db;
Create Table using below Create table Statement
3. Installing CockroachDB Go pq library
CockroachDB uses Postgres database protocol so we have use Go pq driver. To install Go pg driver, run the following command:
go get -u github.com/lib/pq
Note: Make sure that you have GO installed and GOPATH and GOBIN are set in environment variable.
4. Connection to DB
// Connect to the "company_db" database.
db, err := sql.Open("postgres","postgresql://root@localhost:26257/company_db?sslmode=disable")
5. SQL Statement
Insert, Update and Delete can use the same function db.Exec()
//Inserting a Row in to DB.
_, err := db.Exec(`INSERT INTO tbl_employee (full_name, department, designation, created_at, updated_at) VALUES ('Irshad', 'IT', 'Product Manager', NOW(), NOW());`);
Select Statement uses db.Query
//Select statement
rows, err := db.Query("select employee_id, full_name FROM tbl_employee;")
6. Full Source Code
Run the above code and if run successfully it will print the data in the console if not error message would get printed.
To verify the data you can run below statement in CockroachDB SQL Client:
select * from tbl_employee;
As you can see its very easy to start working with CockroachDB in GoLang.
Kindly comment if you have any doubt. I would love to help.