设为首页 收藏本站
查看: 633|回复: 0

[经验分享] golang 查询数据库操作

[复制链接]

尚未签到

发表于 2018-9-20 08:44:50 | 显示全部楼层 |阅读模式
DSC0000.png
  SQL.Open only creates the DB object, but dies not open any connections to the database. If you want to test your connections you have to execute a query to force opening a connection. The common way for this is to call Ping() on your DB object.
  See http://golang.org/pkg/database/sql/#Open and http://golang.org/pkg/database/sql/#DB.Ping
  Quoting from the doc of sql.Open():

  Open may just validate its arguments without creating a connection to the database. To verify that the data source name is valid, call Ping.

  As stated, Open() may not open any physical connection to the database server, but it will validate its arguments. That being said if arguments are valid, it may return nil error even if the database server is not reachable, or even if the host denoted by dataSourceName does not exist.
  To answer your other question:

  What is the point of check for errors after this function if it does not return errors?

  You have to check returned errors because it can return errors. For example if the specified driverName is invalid, a non-nil error will be returned (see below).
  To test if the database server is reachable, use DB.Ping(). But you can only use this if the returned error is nil, else the returned DB might also be nil (and thus calling the Ping()method on it may result in run-time panic):
  

if db, err := sql.Open("nonexistingdriver", "somesource"); err != nil {  fmt.Println("Error creating DB:", err)
  fmt.Println("To verify, db is:", db)
  
} else {
  err = db.Ping()
  if err != nil {
  fmt.Println("db.Ping failed:", err)
  }
  
}
  

  Output (try it on the Go Playground):
  

Error creating DB: sql: unknown driver "nonexistingdriver" (forgotten import?)  
To verify, db is:
  



sql.open("postgres", "postgres://postgres:postgres/xxxx")连接数据库出错的时候,也不会报错, 很奇怪,那这种错误是怎么处理的呢?
  

package main  

  
import (
  "database/sql"
  "fmt"
  _ "github.com/lib/pq"
  "log"
  
)
  

  
var db *sql.DB
  

  
func main() {
  

  defer func() {
  fmt.Println(recover())
  }()
  var ss string
  var err error
  // var err error
  if db != nil {
  db.Close()
  } else {
  db, err = sql.Open("postgres", "postgres://postgres:postgres@127.0.0.1/xinyi?sslmode=disable")
  if err != nil {
  log.Println("Can't connect to postgresql database")
  } else {
  err = db.Ping()
  if err != nil {
  fmt.Println("db.Ping failed:", err)
  }
  }
  err = db.QueryRow("select value from configs where key =$1", "line1_batch").Scan(&ss)
  if err != nil {
  log.Println("query error")
  }
  fmt.Println(ss)
  }
  

  
}
  

  




-----------------------------------------------------------------------------------------------------

https://medium.com/namely-labs/postgres-in-go-cf794adc4c52

SQL Drivers
  Go’s standard library was not built to include any specific database drivers. Here is a list of available third party SQL drivers http://golang.org/s/sqldrivers .

Setup
  First we will need to import the packages that our program will use.
  

import (  “database/sql”
  _ “github.com/lib/pq”
  )
  

  Here, we import the “database/sql” library which provides a generic interface for working with SQL databases. The second import, _”github.com/lib/pq”, is the actual postgresql driver. The underscore before the library means that we import pq without side effects. Basically, it means Go will only import the library for its initialization. For pq, the initialization registers pq as a driver for the SQL interface.

Open
  Next we will need to open the database. It is important to note that calling “Open” does not open a connection to the database. The return from “Open” is a DB type and an error. The DB type represents a pool of connections which the sql package manages for you.
  

db, err := sql.Open(“postgres”,”user=Arnold dbname=TotalRecall sslmode=disable”)  

  “Open” returns an error which validates the arguments of a database open
  

if err != nil {  log.Fatal(“Error: The data source arguments are not valid”)
  }
  

Ping
  Since the error returned from “Open” does not check if the datasource is valid calling Ping on the database is required
  

err = db.Ping()  

if err != nil {  log.Fatal(“Error: Could not establish a connection with the database”)
  }
  

Prepare
  Once the DB has been set up, we can start safely preparing query statements. “Prepare” does not execute the statement.
  

queryStmt, err := db.Prepare(“SELECT name FROM users WHERE>  

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

QueryRow
  We can now “QueryRow” off of the prepared statement and store the returned row’s first column into the “name string”. “QueryRow” only queries for one row.
  

var name string  

err = queryStmt.QueryRow(15).Scan(&name)  

  In addition, a common error check is for “No Rows”. Some programs handle “No Rows” differently from other scanning errors. Errors like this are specific to the library, not Go in general.
  

if err == sql.ErrNoRows {  log.Fatal(“No Results Found”)
  }
  

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

  You can also skip explicitly preparing your Query statements.
  

var lastName string  

err = db.QueryRow(“SELECT last_name FROM users WHERE>  

if err == sql.ErrNoRows {  log.Fatal(“No Results Found”)
  }
  

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

Query
  We can also handle a Query that returns multiple rows and stores the result into a “names” slice. In the code below you will see “rows.Next”, which moves the cursor to the next result row. If there is no next row or error preparing the next row, a false will be returned.
  

var names []string  

rows, err := queryStmt.Query(15)  defer rows.Close()
  

for rows.Next() {  var name string
  

  if err := rows.Scan(&name); err != nil {  log.Fatal(err)
  }
  names = append(names, name)
  }
  

  This next check is for any errors encountered during the iteration.
  

err = rows.Err()  

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

Conclusion
  Golang’s standard sql package is extremely simple, yet powerful. This post covers the basics of the sql package. If you would like to learn more, visit the official docs at: http://golang.org/pkg/database/sql. Feel free to leave any comments or questions.



运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-598602-1-1.html 上篇帖子: Golang里面使用protobuf(proto3) 下篇帖子: golang安装卸载 linux+windows+raspberryPI 平台
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表