Golang SQL Server Database stmt using

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

Use the package "CODE.GOOGLE.COM/P/ODBC"

Database connection Statements

"driver={SQL Server};SERVER="";UID="";PWD="";DATABASE=" + datanameDb, dberr = sql.Open("odbc", conn)

The DB created is actually a connection pool, and a connection to the database is created each time the database is manipulated. So if you break the network after a while, and then execute the query after the disconnection, in fact, will be automatically re-linked.

Data manipulation
1. Enquiry
Method One: Pre-compilation

stmt, errs := Db.Prepare("select * from tbl where col=?")defer stmt.Close()rows, err := stmt.Query(id)defer rows.Close()for rows.Next() {    varvalueint    if ers := rows.Scan(&value); ers == nil {        returnvalue    }}

Method Two: Query queries

rows, errs := Db.Query("select * from tbl where col='"+id+"'")defer rows.Close()for rows.Next() {    varvalueint    if ers := rows.Scan(&value); ers == nil {        returnvalue    }}

2. Increase

Method One: Pre-compilation

stmt, errs := Db.Prepare("insert into tbl (col) values(?)")defer stmt.Close()_, err := stmt.Exec(id)

Method Two:

_, err := DB.Exec("insert into tbl (col) values(='"+id+"')")

3. Modification

Method One: Pre-compilation

stmt, errs := Db.Prepare("update tbl col=? ")defer stmt.Close()_, err := stmt.Exec(id)

Method Two:

_, err := DB.Exec("update tbl col='"+id+"')")

4. Delete

Method One: Pre-compilation

stmt, errs := Db.Prepare("delete from tbl where col=? ")defer stmt.Close()_, err := stmt.Exec(id)

Method Two:

_, err := DB.Exec("delete from tbl where col='"+id+"')")

Through the above can be found in fact (add, delete, modify) The steps of the operation is the same, if the bulk operation is recommended to use prepare way, or direct use of exec more convenient, eliminating the time to create stmt.

A deeper understanding can be viewed
Use of Database/sql stmt

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.