数据库连接 golang mysql

huangapple go评论83阅读模式
英文:

Database Connection golang mysql

问题

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

package database

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

// 定义一个元素的数据类型
type element struct {
    title      string
    date       string
    url        string
    remoteUrl  string
}

// 全局数据库对象
var (
    db *sql.DB
)

// 插入通知数据的函数
func insertNoticeData(elem element, folder string) bool {
    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 {
        fmt.Println("Error preparing statement")
        return false
    }

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

    return true
}

我遇到了一个错误:undefined symbol stmt。我在这里漏掉了什么?

英文:

I am trying to write a test program for my Go code. This code has 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
}

It's giving me an error: undefined symbol stmt

What am I missing here?

答案1

得分: 3

switch语句的case分支中声明的变量的作用域限定在该分支内部,在case之外是无法访问的。

解决方法很简单,只需在switch之前声明stmterr变量,并且使用赋值操作符(=)而不是短变量声明(:=):

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 {
    // 处理错误
}

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

来源于规范:

声明和作用域:

Go使用进行词法作用域:
...

  1. 在函数内部声明的常量或变量标识符的作用域从ConstSpec或VarSpec(对于短变量声明为ShortVarDecl)的结束处开始,并在最内层包含块的结束处结束。

...

以及规范:块:

块是一对匹配的大括号内可能为空的声明和语句序列。

[...] 除了源代码中的显式块外,还有隐式块:

  1. switch语句或select语句中的每个分支都作为一个隐式块。
英文:

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)

Source from the spec:

Declarations and Scope:

> Go is lexically scoped using blocks:
> ...
>
> 5. 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.
>
> ...

And 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:
>
> 5. Each clause in a "switch" or "select" statement acts as an implicit block.

huangapple
  • 本文由 发表于 2016年10月29日 21:56:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/40319810.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定