Working with sql - Sharykhin/go-modular GitHub Wiki
To work with native sql you have to import database package from core
import "go-modular/core/database"
This package has DB variable (*sql.DB), which contains connection to database and provide all necessary methods.
Inserting
Method DB.Exec executes query and if error was occured, return it, or nil
if err :=database.DB.Exec("INSERT INTO TableName(column1, column2) VALUES(value1,value2)"); err != nil {
return err
}
Deleting
if err :=database.DB.Exec("DELETE FROM TableName WHERE column1=value1"); err != nil {
return err
}
Selecting
var data []map[string]interface{}
rows,err := DB.Query("SELECT * FROM TableName")
if err != nil {
return nil,err
}
// Get column names
columns, err := rows.Columns()
if err != nil {
return nil,err
}
// Make a slice for the values
values := make([]sql.RawBytes, len(columns))
// rows.Scan wants '[]interface{}' as an argument, so we must copy the
// references into such a slice
// See http://code.google.com/p/go-wiki/wiki/InterfaceSlice for details
scanArgs := make([]interface{}, len(values))
for i := range values {
scanArgs[i] = &values[i]
}
// Fetch rows
for rows.Next() {
// Initilize map, which will be responsible for saving data of each row
rowData := make(map[string]interface{})
// get RawBytes from data
err = rows.Scan(scanArgs...)
if err != nil {
return nil,err
}
// Now do something with the data.
// Here we just print each column as a string.
var value string
for i, col := range values {
// Here we can check if the value is nil (NULL value)
if col == nil {
value = "NULL"
} else {
value = string(col)
}
// Fill map, where key will be column name
rowData[columns[i]]=value
}
// Fill our returning slice
data = append(data,rowData)
}
if err := rows.Err(); err != nil {
return nil,err
}
return data
To know more about working with sql read tutorial