Created
May 31, 2018 15:25
-
-
Save irshadhasmat/cc2fc1ee9e6efbfb739feeb7d3d9f95c to your computer and use it in GitHub Desktop.
Code Snippet to perform CRUD operation in Go Lang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"database/sql" | |
"fmt" | |
"log" | |
_ "github.com/lib/pq" | |
) | |
func main() { | |
// Connect to the "company_db" database. | |
db, err := sql.Open("postgres", "postgresql://root@localhost:26257/company_db?sslmode=disable") | |
if err != nil { | |
log.Fatal("error connecting to the database: ", err) | |
} | |
// Insert a row into the "tbl_employee" table. | |
if _, err := db.Exec( | |
`INSERT INTO tbl_employee (full_name, department, designation, created_at, updated_at) | |
VALUES ('Irshad', 'IT', 'Product Manager', NOW(), NOW());`); err != nil { | |
log.Fatal(err) | |
} | |
// Select Statement. | |
rows, err := db.Query("select employee_id, full_name FROM tbl_employee;") | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer rows.Close() | |
for rows.Next() { | |
var employeeID int64 | |
var fullName string | |
if err := rows.Scan(&employeeId, &fullName); err != nil { | |
log.Fatal(err) | |
} | |
fmt.Printf("Employee Id : %d \t Employee Name : %s\n", employeeId, fullName) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment