gpt4 book ai didi

mysql - 数据库连接 golang mysql

转载 作者:IT王子 更新时间:2023-10-29 01:38:57 25 4
gpt4 key购买 nike

我正在尝试为我的 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

我在这里错过了什么?

最佳答案

switchcase 分支中声明的变量语句在 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.

关于mysql - 数据库连接 golang mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40319810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com