Golang 獲取MySQL表元資訊

2021-10-05 17:18:09 字數 2617 閱讀 1178

本文介紹golang如何運算元據庫,並通過獲取mysql表元資訊進行例項演示。

golang 通過標準database/sql包實現了對關係型資料庫很好的支援,如mysql, ms sql server, oracle 和 postgres,當然nosql也沒有問題,如mongodb、redis。

使用golang標準庫可以很容易與mysql互動,其他資料庫也一樣,可以參加golang資料庫驅動列表。

sql標準庫提供通用介面及常用方法用於訪問或運算元據庫。資料庫包包括連線池,正確使用可確保執行緒安全。資料庫包必須和具體資料庫驅動包一起使用。

連線mysql需要使用標準sql包和mysql驅動,mysql驅動包實現標準包方法和介面。一般實現sql標準包通常通過標準包暴露驅動介面,入口點**在sql驅動的go檔案。

sql包是存在於go標準庫中的標準sql包。因為init()函式是在任何其他函式之前執行的,所以可以肯定的是,只要在**中包含了mysql包,則mysql驅動會被自動註冊並通過標準sql包呼叫。

)這裡下劃線_表示載入包但不直接使用,我們通過標準sql包使用。沒有下劃線,編譯器會提示匯入沒有使用錯誤。

載入包的動作即使是靜態方式,但包中的init()方法仍會執行,初始化方法會註冊mysql驅動給標準包,從而使用對標準包的方法呼叫轉為對具體mysql實現的方法呼叫。

為了資料庫處理物件可以重用,定義全域性資料庫處理指標:

var db *sql.db
與資料庫互動的第乙個函式是sql.open(),獲取資料庫物件,用於執行查詢和命令。第乙個引數指定資料庫驅動,這裡是mysql。第二個引數是連線字串。

db, err = sql.open("mysql", "root:pass123@/sakila?charset=utf8&parsetime=true")
sql.open()函式返回資料庫連線處理器,用於對資料庫執行查詢和命令。同時返回錯誤物件,沒有錯誤則為nil。

連線字串包括使用者名稱和密碼,這裡還指定字符集和解析時間型別,完整內容請參考官網。

在init方法中呼叫open方法:

func init()
檢查錯誤方法:

func checkerr(err error) 

}

獲取元資訊主要包括獲取資料庫中表資訊以及表的字段資訊。從information_schema.tables表中查詢表資訊:

select table_name name,ifnull(table_comment,table_name) value

from information_schema.tables

where upper(table_type)='base table'

and lower(table_schema) = 'sakila'

order by table_name asc;

獲取表字段資訊,從information_schema.columns表查詢字段資訊:

select column_name fname,column_comment fdesc,data_type datatype,

is_nullable isnull,ifnull(character_maximum_length,0) slength

from information_schema.columns

where table_schema = 'sakila' and table_name = 'actor';

使用?作為引數佔位符,db.query()執行查詢,引數為sql字串和資料庫名。

func tableinfo(dbname string) map[string]string  

result[tablename] = tabledesc

} return result

}

遍歷查詢結果,資料庫名稱和注釋資訊作為鍵值對儲存在map中。

定義fieldinfo函式,引數為資料庫名和表名,返回field型別切片,我們首先看field結構體:

type field struct
查詢字段函式fieldinfo():

func fieldinfo(dbname,tablename string)  field

return result

}

下面在main函式中進行測試:

func main() 

}

defer db.close()語句確保執行完畢後關閉資料庫連線。

本文介紹了標準database/sql包及mysql驅動,最後通過獲取mysql表元資訊示例說明如何執行資料庫操作。

Mysql 獲取表資訊 獲取表詳情

查詢資料庫表結構 select table schema as 資料庫名 table name as 資料表名 create time as 建立時間 table comment as 描述 from information schema.tables where table schema 資料庫名...

MySQL獲取錶行數

1.獲取單錶的行數select count from table name 2.獲取多表的行數 可以使用 union 運算子組合每個select語句返回的結果集 select tablename1 tablename,count rows from table name1 union select ...

golang學習 獲取URL

執行命令 go run main.go 這個程式從兩個package中匯入了函式,net http和io ioutil包,http.get函式是建立http請求 的函式,如果獲取過程沒有出錯,那麼會在resp這個結構體中得到訪問的請求結果。resp的 body欄位包括乙個可讀的伺服器響應流。iout...