Skip to content

Instantly share code, notes, and snippets.

@tappoz
Last active August 16, 2017 12:24
Show Gist options
  • Save tappoz/5b9fe04e105dcf9b5214e6da6aedf990 to your computer and use it in GitHub Desktop.
Save tappoz/5b9fe04e105dcf9b5214e6da6aedf990 to your computer and use it in GitHub Desktop.
Go code snippets

Go database operations

The following go/golang snippet:

  • connect to a MS-SQL database via ODBC;
  • INSERTs a new record into a table;
  • disconnects from the database.
package main

import _ "github.com/denisenkom/go-mssqldb" // SQL Server driver
import "database/sql"
import "fmt"
import "time"

var insertReadingsSql = `
  INSERT INTO <TABLE_NAME> (<STR_COLUMN>, <TIMESTAMP_COLUMN>, <NUMERIC_COLUMN>)
    VALUES ('%s', '%s', %f);`

func main() {
  // `log=63` parameter is to make the SQL connector verbose while executing SQL statements
  odbcStr := "server=<SERVER_URL>;user id=<USERNAME>;password=<PSW>;database=<DB_NAME>;log=63"
  rawDB, connStrError := sql.Open("mssql", odbcStr)
  if connStrError != nil {
    rawDB.Close()
    panic(connStrError)
  }

  sqlStr = fmt.Sprintf(insertReadingsSql, "foo", time.Now().Format(time.RFC3339Nano), 42.0)

  _, err := rawDB.Exec(sqlStr)
  if err != nil {
    rawDB.Close()
    panic(err)
  }

  rawDB.Close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment