Ezio Ezio - 1 month ago 11
MySQL Question

Database Connection golang mysql

I am trying to write a test program for my go code
This code have a global db variable which i initialize in the main package

package database

import(
"database/sql"
_ "github.com/go-sql-driver/mysql"
)

//Data type that defines one identity
type element struct {
title string
date string
url string
remoteUrl string
}


//global database object for every package
var (
db *sql.DB
)

// params elem : element to be inserted , folder : folderName
func insertNoticeData( elem element, folder string) bool {

switch folder {
case "Results" : stmt, err := db.Prepare("INSERT results_ipu SET title=?, date=?, url=?, remoteUrl=?")
case "Notices" : stmt, err := db.Prepare("INSERT notice_ipu SET title=?, date=?, url=?, remoteUrl=?")
case "Datesheets" : stmt, err := db.Prepare("INSERT datesheet_ipu SET title=?, date=?, url=?, remoteUrl=?")
}

res, err1 := stmt.Exec(elem.title, elem.date, elem.url, elem.remoteUrl)
if err1 != nil {
fmt.Println("Error inserting in database ")
return false
}
return true
}


its giving me an error that undefined symbol stmt
what am i missing here ?

Answer

Variables declared in the case branches of a switch statement are scoped to the case branch, they are not accessible (not in scope) outside of the case.

Solution is simple, declare stmt and the err variables before the switch, and use assignment (=) instead of the short variable declarations (:=):

var stmt *sql.Stmt
var err error

switch folder {
    case "Results" : stmt, err = db.Prepare("INSERT results_ipu SET title=?, date=?, url=?, remoteUrl=?")
    case "Notices" : stmt, err = db.Prepare("INSERT notice_ipu SET title=?, date=?, url=?, remoteUrl=?")
    case "Datesheets" : stmt, err = db.Prepare("INSERT datesheet_ipu SET title=?, date=?, url=?, remoteUrl=?")
}

if err != nil {
    // handle error
}

res, err1 := stmt.Exec(elem.title, elem.date, elem.url, elem.remoteUrl)
Comments