Go database/sql sql-driver/mysql operation

Source: Internet
Author: User
Tags bulk insert rollback stmt throw exception

The Github.com/go-sql-driver/mysql is used here,

So you need to download a github.com/go-sql-driver/mysql

Introduction of Database/sql and Github.com/go-sql-driver/mysql

The implementation of the database of the increase, deletion, change, check, business

Here directly on the code, the code has a detailed explanation. And these operations have been actually manipulated by me.

Introduce the required packages

Import (    "database/sql"    _"github.com/ Go-sql-driver/mysql"    " "log""    strconv     " // "Reflect"     // gets the variable type used )

Increase:

Func Main () {//InsertName: ="name"pwd:="Password"Nickname:="Nickname"Db,err:= SQL. Open ("MySQL","Go_mysql_user:[email protected] (localhost:3306)/go_mysql?charset=utf8")    ifErr! =nil{Panic (err. Error ()) log. PRINTLN (ERR)return} defer db. Close ()//only in the front with panic[throw exception] then defer can function, if the link data when the problem, he will write data to err. Defer: delay, here immediately apply for a close SQL link to the grass error, defer after the method, or deferred execution. When a function throws an exception, it is executedInsert_sql: ="INSERT into Users (name,pwd,nickname) value (?,?,?), (?,?,?), (?,?,?), (?,?,?)"Stmt,err:= db. Prepare (Insert_sql)//prepares a SQL operation, returns a *stmt, executes after the user, the Stmt can be executed multiple times, or concurrently execute    /** The Main method of this stmt: Exec, Query, Queryrow, Close*/    ifErr! =Nil {log. PRINTLN (ERR)return} res,err:=stmt. Exec (Name,pwd,nickname,name,pwd,nickname,name,pwd,nickname,name,pwd,nickname)ifErr! =Nil {log. PRINTLN (ERR)return} lastinsertid,err:= Res. Lastinsertid ()//when BULK INSERT, Lastinserid returns the first ID, and a single insert returns the ID of this one.//Lastinsertid,err: = Res. Rowsaffected ()//inserts the number of inserted bars after the rowsaffected is returned    ifErr! =Nil {log. PRINTLN (ERR)return     }    //log. Println (reflect. TypeOf (Lastinsertid))//Print Variable typeLast_insert_id_string: = StrConv. Formatint (Lastinsertid,Ten)//int64 to string need to introduce StrConv packageLog. Println ("Lastinsertid ="+last_insert_id_string)}

By deleting:

Func Main () {    //Delete    'delete from users where id=? "     del_stmt,del_err:= db. Prepare (del_sql)    del_stmt. Exec (6)// do not return any results }

Change:

Func Main () {//UpdateUpdate_sql: ="Update users set name=? where id=?"Update_stmt,update_err:=db. Prepare (Update_sql)ifUpdate_err! =Nil {log. Println (Update_err)return; } Update_res,update_err:= update_stmt. Exec ("username",9)    ifUpdate_err! =Nil {log. Printf ("%v", Update_err)return} affect_count,_:= Update_res. Rowsaffected ()//returns the number of affected bars, noting that there are two return valuesLog. Printf ("%v", Affect_count)}

Check One:

Type Userstruct{IDintnamestringpwdstringNicknamestring}func Main () {//Select    varUser User select_sql:="SELECT * from users where ID >?"Select_err:= db. Queryrow (Select_sql, One). Scan (&user.id,&user.name,&user.pwd,&user.nickname)//query a bar to return a result. and assigns to the user this struct type of variable, even if the query is more than one, the single return is a    ifSelect_err! = Nil {//If no data is queried, enter if err:no rows in result setlog. Println (Select_err)return} log. PRINTLN (user)}

Check Multiple articles:

Func Main () {//Querying multiple linesSelect_rows,select_err: = db. Query (Select_sql, -)    ifSelect_err! =Nil {log. Println (Select_err)return} defer select_rows. Close () forselect_rows. Next () {varIdint        varNamestring        varPwdstring        varNicknamestring        ifERR: = Select_rows. Scan (&id,&name,&pwd,&nickname); Err! =Nil {log. PRINTLN (ERR)return} log. Printf ("Id=%v,name=%v,pwd=%v,nickname=%v", Id,name,pwd,nickname)}}

Transaction:

Func Main () {//TransactionsTx,err: = db. Begin ()//declares the beginning of a transaction    ifErr! =Nil {log. PRINTLN (ERR)return} insert_sql:="INSERT into Users (name,pwd,nickname) value (?,?,?)"Insert_stmt,insert_err:=TX. Prepare (Insert_sql)ifInsert_err! =Nil {log. Println (Insert_err)return} insert_res,insert_err:= insert_stmt. Exec ("Tx_name","tx_pwd","Tx_nickname") Last_insert_id,_:=Insert_res. Lastinsertid () log. PRINTLN (last_insert_id) defer TX. Rollback ()//The last_login_id before the rollback was there, but after the rollback the operation was not committed and was rolled back, so the above printed last_login_id data is not present in the database table//Tx.commit ()//This commits the above operation, so the SQL executed above will produce a data in the database}

Knowledge points Summary and precautions:

Db,err: = sql. Open ("MySQL", "Database login: Database password @tcp (server: Port)/database name Charset=utf8") corresponding to the modification;
Defer db. The Close () defer is an operation that is deferred or abnormally performed. This indicates that there is an exception to turn off DB with panic (err. Error ()) = "Throws an exception. Use it together.
Lastinsertid () Gets the ID that inserts the first article is useful
Rowsaffected () Gets the number of affected/inserted bars useful
Reflect. TypeOf (i) The type of variable i is returned in the reflect package TypeOf
StrConv. Formatint (Int64 bit variable, ten) StrConv package formatint The variable of the int64 bit into a string specifically with another article summarizing
Others are returned in code with some return values and are used.

Good night, ~~gogogo.

Go database/sql sql-driver/mysql operation

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.