上QQ阅读APP看书,第一时间看更新
The defer and panic statements
The defer statement defers the execution of the function until the surrounding function returns. The panic function stops the current flow and control. Deferred functions are executed normally after the panic call. In the following code example, the defer call gets executed even when the panic call is invoked:
defer database.Close()
return customer
}
// 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
}
Let's take a look at the InsertCustomer, UpdateCustomer, and DeleteCustomer methods in the following sections.