数据库连接 golang mysql

Database Connection golang mysql

我正在尝试为我的 Go 代码编写一个测试程序。这段代码有一个全局 db 变量,我在 main 包中对其进行了初始化。

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
}

它给我一个错误:undefined symbol stmt

我在这里错过了什么?

switch 语句的 case 分支中声明的变量 范围 到 case 分支,它们在外部不可访问(不在范围内) case.

解决方法很简单,在switch之前声明stmterr变量,然后使用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)

来自规范的来源:

Declarations and Scope:

Go is lexically scoped using blocks:
...

  1. The scope of a constant or variable identifier declared inside a function begins at the end of the ConstSpec or VarSpec (ShortVarDecl for short variable declarations) and ends at the end of the innermost containing block.

...

Spec: Blocks:

A block is a possibly empty sequence of declarations and statements within matching brace brackets.

[...] In addition to explicit blocks in the source code, there are implicit blocks:

  1. Each clause in a "switch" or "select" statement acts as an implicit block.