将“ SELECT *”列(不止一个)读入go中的[] []字符串

时间:2019-07-08 06:18:34

标签: mysql go

我想在Go的[] [] string中插入MySQL数据库列,这是一个类似的代码,它仅对一个列执行此操作,然后将其插入[] string中,但是我需要在[] [] string中添加更多列制作一个数据框。

mysql> select * from users;
+----+-----------+----------+----------+-------------------------------+--------------+
| id | fname     | lname    | uname    | email                         | contact      |
+----+-----------+----------+----------+-------------------------------+--------------+
|  1 | Rishikesh | Agrawani | hygull   | rishikesh0014051992@gmail.com | 917353787704 |
|  2 | Sandeep   | E        | sandeep  | sandeepeswar8@gmail.com       | 919739040038 |
|  3 | Darshan   | Sidar    | darshan  | sidardarshan@gmail.com        | 917996917565 |
|  4 | Surendra  | Prajapat | surendra | surendrakgadwal@gmail.com     | 918385894407 |
|  5 | Mukesh    | Jakhar   | mukesh   | mjakhar.kjahhar@gmail.com     | 919772254140 |
+----+-----------+----------+----------+-------------------------------+--------------+
5 rows in set (0.00 sec)

mysql> 
func main() {
    // db, err := sql.Open("mysql", "<username>:<password>@tcp(127.0.0.1:<port>)/<dbname>?charset=utf8" )
    db, err := sql.Open("mysql", "hygull:admin@67@tcp(127.0.0.1:3306)/practice_db?charset=utf8")

    if err != nil {
        log.Fatal(err)
    }

    rows, err := db.Query("select fname from users")

    if err != nil {
        log.Fatal(err)
    }

    firstnames:=[]string{}
    for rows.Next() {
        var fname string
        rows.Scan(&fname)
        firstnames = append(firstnames, fname)
    }

    fmt.Println(firstnames)
    db.Close()
}

1 个答案:

答案 0 :(得分:1)

假设您的查询返回4列,您只需一次扫描多个值。

<p:selectBooleanCheckbox id="fixedLossId" value="#{chargebackBean.selectedChargebackCategory.fixedLoss}">
    <p:ajax event="change" update="fixedLossDateTime" oncomplete="fixedLoss()" />
</p:selectBooleanCheckbox>

<script>
    function fixedLoss() {
        if (fixedLossSelected ??) {
            ...
        }
        else {
            ...
        }
    }
</script>

如果列数不是静态的,则可以执行以下操作使其自动化,而不是手动扩展指针:

details:=[][]string{}
for rows.Next() {
    cols := make([]string, 4) 
    rows.Scan(&cols[0], &cols[1], &cols[2], &cols[3])
    details = append(details, cols)
}