Golang Querying database operations

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Sql. Open only creates the DB object, but dies not open any connections to the database. If you want to test your connections, you had to execute a query to force opening a connection. The common-on-a-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 sql.Open() of:

Open may just validate it arguments without creating a connection to the database. To verify this data source name is valid and call Ping.

As stated, May isn't Open() open any physical connection to the database server, but it'll validate its arguments. That being said if arguments be valid, it may return nil error even if the database server was not reachable, or even if The host denoted by dataSourceName does not exist.

To answer your other question:

What are the point's check for errors after this function if it does not return errors?

You have the to check returned errors because it can return errors. For example if the specified driverName is invalid, a non-nil error would be returned (see below).

To test if the database server was reachable, DB.Ping() use. But can only use this if the returned error nil is, else the returned DB might also be nil (and thus calling th E Ping() method on it could result in run-time panic):

IfDb,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 { Fmtprintln (, Err  }< Span class= "PLN" >}            

Output (Try it on the Go Playground):

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

Sql.open ("Postgres", "postgres://postgres:postgres/xxxx") connection database error, also do not error, very strange, that this error is how to deal with it?

The package Mainimport ("Database/sql" "Fmt" _ "GITHUB.COM/LIB/PQ" "Log") var db *sql. Dbfunc Main () {defer func () {fmt. Println (Recover ())} () var ss stringvar err error//var err errorif 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 is not built to include any specific database drivers. Here are a list of available third party SQL drivers http://golang.org/s/sqldrivers.

Setup

First we'll need to import the packages.

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 would only be import the library for its initialization. For PQ, the initialization registers PQ as a driver for the SQL interface.

Open

Next we'll need to open the database. It's important to note, 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 is not valid")
}

Ping

Since the error returned from ' Open ' does not check if the datasource are 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 id=$1")
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 was for "No Rows". Some programs handle "No Rows" differently from other scanning errors. Errors like this is specific to the library and 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 id=$1", 15). Scan (&lastname)
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'll 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 would 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 was 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 as to learn more, visit the official Docs at:http://golang.org/pkg/database/sql. Feel free to leave any comments or questions.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.