Go(又稱Golang)是Google開發的靜態強型別、編譯型、並髮型,並具有垃圾回收功能的程式語言。下面就來由go入門教學欄位介紹一些關於mysql的操作。
go操作mysql資料庫,用的函式庫是go-sql-driver/mysql,安裝直接go get
go get -u github.com/go-sql-driver/mysql
sql.DB
DB型別可用的函式有:
1、Query(c string, args interface{} …) (*Rows, error),常用於SELECT語句
2、Exec(c string, args interface{} …) (*Rows, error),常用與UPDATE和INSERT
3、Prepare(c string) (*Stmt, error),其他語句,也可以用來執行上述語句,傳回Stmt指標
sql.Stmt
#Stmt是準備好的語句,可以執行資料庫語句運算,常用函數有:
Exec(args interface{} …) (Result, error),給定參數並執行準備好的語句,然後傳回語句的總結果
//... stmt, err := db.Perpare("INSERT INTO User(user,pwd) VALUES (?, ?)") if err != nil { panic(err) } defer stmt.Close() _, err := stmt.Exec("laoli", "123456") if err != nil { panic(err) } //... //... stmt, err := db.Perpare("DELETE FROM User") if err != nil { panic(err) } defer stmt.Close() _, err := stmt.Exec() if err != nil { panic(err) }
Query(args interface{} …) ( *Rows, error),給定參數並執行準備好的語句,傳回行結果,比方說SELECT操作就必須用這個函數呼叫。
sql.Rows
Rows是sql語句執行傳回的表,Rows會佔用緩存,Rows.Next()裡,如果傳回false,則會自動釋放快取.
看一下原始碼:
// 源码 func (rs *Rows) Next() bool { var doClose, ok bool withLock(rs.closemu.RLocker(), func() { doClose, ok = rs.nextLocked() }) if doClose { rs.Close() //在这里释放掉了 } return ok }
範例:
package main import ( "database/sql" _ "github.com/go-sql-driver/mysql" ) var db *sql.DB func mian() { db = sql.Open("mysql", "root:123456@tcp(127.0.0.1)/test") if err := db.Ping(); err != nil { panic(err) } } func Insert() { _, err := db.Exec("INSERT INTO User(user, pwd) VALUE (?, ?)", "laowang", "123456") if err != nil { panic(err) } } func SelectRow() { rows, err := db.Query("SELECT * FROM User WHERE user=?", "laowang") if err != nil { panic(err) } //defer rows.Close() //如果后面代码没有循环调用rows.Next(),就需要手动在这里释放一下,不然会一直占用缓存 var user string var pwd string for rows.Next() { row.Scan(&user, &pwd) } print(user, pwd) }
更多go語言知識請關注php中文網go語言教學欄位。
以上是golang mysql操作介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Gohandlesinterfacesandtypeassertionseffectively,enhancingcodeflexibilityandrobustness.1)Typeassertionsallowruntimetypechecking,asseenwiththeShapeinterfaceandCircletype.2)Typeswitcheshandlemultipletypesefficiently,usefulforvariousshapesimplementingthe

Go語言的錯誤處理通過errors.Is和errors.As函數變得更加靈活和可讀。 1.errors.Is用於檢查錯誤是否與指定錯誤相同,適用於錯誤鏈的處理。 2.errors.As不僅能檢查錯誤類型,還能將錯誤轉換為具體類型,方便提取錯誤信息。使用這些函數可以簡化錯誤處理邏輯,但需注意錯誤鏈的正確傳遞和避免過度依賴以防代碼複雜化。

tomakegoapplicationsRunfasterandMorefly,useProflingTools,leverageConCurrency,andManageMoryfectily.1)usepprofforcpuorforcpuandmemoryproflingtoidentifybottlenecks.2)upitizegorizegoroutizegoroutinesandchannelstoparalletaparelalyizetasksandimproverperformance.3)

go'sfutureisbrightwithtrendslikeMprikeMprikeTooling,仿製藥,雲 - 納蒂維德象,performanceEnhancements,andwebassemblyIntegration,butchallengeSinclainSinClainSinClainSiNgeNingsImpliCityInsImplicityAndimimprovingingRornhandRornrorlling。

goroutinesarefunctionsormethodsthatruncurranceingo,啟用效率和燈威量。 1)shememanagedbodo'sruntimemultimusingmultiplexing,允許千sstorunonfewerosthreads.2)goroutinessimproverentimensImproutinesImproutinesImproveranceThroutinesImproveranceThrountinesimproveranceThroundinesImproveranceThroughEasySytaskParallowalizationAndeff

purposeoftheInitfunctionoIsistoInitializeVariables,setUpConfigurations,orperformneccesSetarySetupBeforEtheMainFunctionExeCutes.useInitby.UseInitby:1)placingitinyourcodetorunautoamenationally oneraty oneraty oneraty on inity in ofideShortAndAndAndAndForemain,2)keepitiTshortAntAndFocusedonSimImimpletasks,3)

Gointerfacesaremethodsignaturesetsthattypesmustimplement,enablingpolymorphismwithoutinheritanceforcleaner,modularcode.Theyareimplicitlysatisfied,usefulforflexibleAPIsanddecoupling,butrequirecarefulusetoavoidruntimeerrorsandmaintaintypesafety.

在Go中使用recover()函數可以從panic中恢復。具體方法是:1)在defer函數中使用recover()捕獲panic,避免程序崩潰;2)記錄詳細的錯誤信息以便調試;3)根據具體情況決定是否恢復程序執行;4)謹慎使用,以免影響性能。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

Atom編輯器mac版下載
最受歡迎的的開源編輯器

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!