Learn Data Structures and Algorithms with Golang
上QQ阅读APP看书,第一时间看更新

The GetCustomer method

The GetCustomer method retrieves the Customer data from the database. To start with, the create database operation is shown in the following example. Customer is the table with the Customerid, CustomerName, and SSN attributes. The GetConnection method returns the database connection, which is used to query the database. The query then returns the rows from the database table. In the following code, database operations are explained in detail (database_operations.go):

//main package has examples shown
// in Hands-On Data Structures and algorithms with Go book
package main

// importing fmt,database/sql, net/http, text/template package
import (
"fmt"
"database/sql"
_ "github.com/go-sql-driver/mysql"
)

// Customer Class
type Customer struct {
CustomerId int
CustomerName string
SSN string
}
// GetConnection method which returns sql.DB
func GetConnection() (database *sql.DB) {
databaseDriver := "mysql"
databaseUser := "newuser"
databasePass := "newuser"
databaseName := "crm"
database, error := sql.Open(databaseDriver, databaseUser+":"+databasePass+"@/"+databaseName)
if error != nil {
panic(error.Error())
}
return database
}
// GetCustomers method returns Customer Array
func GetCustomers() []Customer {
var database *sql.DB
database = GetConnection()

var error error
var rows *sql.Rows
rows, error = database.Query("SELECT * FROM Customer ORDER BY Customerid DESC")
if error != nil {
panic(error.Error())
}
var customer Customer
customer = Customer{}

var customers []Customer
customers= []Customer{}
for rows.Next() {
var customerId int
var customerName string
var ssn string
error = rows.Scan(&customerId, &customerName, &ssn)
if error != nil {
panic(error.Error())
}
customer.CustomerId = customerId
customer.CustomerName = customerName
customer.SSN = ssn
customers = append(customers, customer)
}

defer database.Close()

return customers
}

//main method
func main() {

var customers []Customer
customers = GetCustomers()
fmt.Println("Customers",customers)

}

Run the following commands:

go run database_operations.go

The following screenshot displays the output:

Let's take a look at the InsertCustomer method in the next section.