Go连接及操作MySQL-表多查询

package main

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

)

var db *sql.DB

func initDB() (err error) {
dsn :="jbjb:123456@tcp(192.168.8.177:3306)/jbjb"
db, err = sql.Open("mysql", dsn)
if err != nil{

	fmt.Printf("Open %s failed, err:%v\n", dsn, err)
	return
}

err = db.Ping()
if err != nil{
	return
}
return	
}

type runoob_tbl struct{

	runoob_id int
	runoob_title string
	runoob_author string
}

func queryMulti(n int) {
	sqlStr := "SELECT runoob_id, runoob_title, runoob_author FROM runoob_tbl where runoob_id > ?"
	rows, err := db.Query(sqlStr, n)
	if err != nil {
		fmt.Printf("query failed, err:%v\n", err)
		return
	}
	// 非常重要:关闭rows释放持有的数据库链接
	defer rows.Close()

	// 循环读取结果集中的数据
	for rows.Next() {
		var u1 runoob_tbl
		err := rows.Scan(&u1.runoob_id, &u1.runoob_title, &u1.runoob_author)
		if err != nil {
			fmt.Printf("scan failed, err:%v\n", err)
			return
		}
		fmt.Printf("u1:%#v\n", u1)
	}
}

func main() {
	err := initDB() // 调用输出化数据库的函数
	if err != nil {
		fmt.Printf("init db failed,err:%v\n", err)
	}

    fmt.Println("链接成功")
	//queryOne(2)
	queryMulti(0)
}

你可能感兴趣的:(GO)