在Go语言中,”else”条件似乎不起作用。

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

Else condition seems not working in go

问题

我有一个MySQL数据库,其中有一个值,一个字符串:"192.168.0.1"。

以下是我的代码:

package main

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

func checkErr(err error) {
    if err != nil {
        panic(err)
    }
}

func main() {
    db, err := sql.Open("mysql", "be:me@tcp(127.0.0.1:3306)/ipdb?charset=utf8")
    checkErr(err)

    ip := "'192.168.0.1'"
    rows, err := db.Query("SELECT * FROM Ip_ipdata WHERE ipHost=" + ip)
    fmt.Println("insert")
    if rows != nil {
        for rows.Next() {
            var id int
            var ip string
            err = rows.Scan(&id, &ip)
            checkErr(err)
            fmt.Println(id)
            fmt.Println(ip)
        }
    } else {
        fmt.Println("insert2")
        stmt, err2 := db.Prepare("INSERT Ip_ipdata SET ipHost=2")
        checkErr(err2)

        _, err3 := stmt.Exec(ip)
        checkErr(err3)
    }
    fmt.Println("end")
}

当我将"'192.168.0.1'"放入ip中时,它可以正常工作并显示预期结果。

但是,当我将"'192.168.0.2'"放入ip中时,else语句没有运行,程序就退出了。

它没有打印"insert2"。

截图1
截图2

英文:

I have a MySQL database with one value in it, a string: "192.168.0.1"

Here is my code:

package main

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

func checkErr(err error) {
    if err != nil {
        panic(err)
    }
}
func main() {
    db, err := sql.Open("mysql", "be:me@tcp(127.0.0.1:3306)/ipdb?charset=utf8")
    checkErr(err)

    ip := "'192.168.0.1'"
    rows, err := db.Query("SELECT * FROM Ip_ipdata WHERE ipHost=" + ip)
    fmt.Println("insert")
    if rows != nil {
        for rows.Next() {
            var id int
            var ip string
            err = rows.Scan(&id, &ip)
            checkErr(err)
            fmt.Println(id)
            fmt.Println(ip)
        }

    } else {
        fmt.Println("insert2")
        stmt, err2 := db.Prepare("INSERT Ip_ipdata SET ipHost=2")
        checkErr(err2)

        _, err3 := stmt.Exec(ip)
        checkErr(err3)
    }
    fmt.Println("end")
}

When I put "'192.168.0.1'" in ip it works and shows as expected.

But when I put "'192.168.0.2'" in ip the else statement isn't run and it just exits.

It didn't print "insert2"

screenshot 1
screenshot 2

答案1

得分: 3

你应该习惯使用'?'占位符来编写你的SQL语句,以便进行适当的转义并防止潜在的SQL注入攻击。

在使用返回值之前,你应该始终检查Go中的错误。

ip := "192.168.0.1"
rows, err := db.Query("SELECT * FROM Ip_ipdata WHERE ipHost=?", ip)
if err != nil {
// 处理错误
}
// 这将确保将数据库连接放回连接池中
defer rows.Close()

for rows.Next() {
// 在这里进行扫描操作
}

英文:

You should get used to using '?' placeholders in your sql to allow for proper escaping and prevent any potential SQL injection attacks.

You should always check the error in Go before using the returned value.

ip := "192.168.0.1"
rows, err := db.Query("SELECT * FROM Ip_ipdata WHERE ipHost=?", ip)
if err != nil {
    // handle error
}
// this will ensure that the DB connection gets put back into the pool
defer rows.Close()

for rows.Next() {
    // scan here
}

答案2

得分: 0

Query返回的Rows在没有结果的情况下不会是nil,而是空的。可以尝试像这样写:

func main() {
    ...
    fmt.Println("insert")
    checkErr(err)
    defer rows.Close()
    var found bool
    for rows.Next() {
        found = true
        ...
    }

    if !found {
        fmt.Println("insert2")
        ...
    }
    fmt.Println("end")
}

请注意,像@jmaloney所说,更健壮的错误处理是必须的,同时记得关闭你的Rows指针。

英文:

The Rows returned by Query will not be nil in the case of no results, it will be empty. Try something like this:

func main() {
    ...
    fmt.Println("insert")
    checkErr(err)
    defer rows.Close()
    var found bool
    for rows.Next() {
        found = true
        ...
    }

    if !found {
        fmt.Println("insert2")
        ...
    }
    fmt.Println("end")
}

Note that like @jmaloney said, more robust error handling is a must as is closing your Rows pointer.

huangapple
  • 本文由 发表于 2017年6月20日 02:55:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/44637932.html
匿名

发表评论

匿名网友

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

确定