2016-10-29 140 views
2

我想为我的Go代码写一个测试程序。此代码有一个全局变量db,我在main包中进行了初始化。数据库连接golang mysql

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

缺少什么我在这里?

回答

3

switch声明case分支声明的变量是作用域的情况下分支,它们不是case的外部访问(不在范围内)。

解决方案简单,switch之前申报stmterr变量,并使用assignment=)代替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.
+0

感谢队友 刚开始golang几天前所以还是一个新手:P – Ezio