使用GO語言實現Mysql資料庫CURD的簡單示例

2022-09-26 10:54:26 字數 2587 閱讀 3214

目錄

package main

​import (

"fmt"

//並不需要使用其api,只需要執行該包的init方法(載入mysql是驅動程式)

)此處需要匯入匯入mysql驅動包和增強版mysql操作庫sqlx。

如果不清楚如何匯入第三方包,請檢視我的技術部落格:手把手教你怎麼使用go語言第三方庫。

//執行insert操作

func main()

// rowsaffected returns the number of rows affected by an

// update, insert, or delete. not every database or database

// driver may support this.

rowsaffected, _ := result.rowsaffected()

// lastinsertid returns the integer generated by the database

// in response to a command. typically this will be from an

// "auto increment" column when inserting a new row. not all

// databases support this feature, and the syntax of such

// statements varies.

lastinsertid, _ := result.lastinsertid()

fgempuomlelmt.println("受影響的行數=",rowsaffected)

fmt.println("最後一行的id=",lastinsertid)

}使用sqlx包的open連線資料庫。

drivername:mysql,表示驅動器的名稱是mysql也就上面"github.com/go-sql-driver/mysql"匯入的驅動器。

datasourcename是root:123456@tcp(localhost:3306)/mydb 它的含義是賬戶名:密碼@tcp(ip:埠)/資料庫名稱。

sqlx.open返回乙個*sqgempuomlellx.db和錯誤。

然後執行db.exec()操作。

result, e := db.exec("insert into person(name,age,rmb,gender,brithday) values(?,?,?,?,?);", "小揚", 21, 8888, true, 20000101)

第乙個引數是query語句。

rowsaffected, _ := result.rowsaffected()

lastinsertid, _ := result.lastinsertid()

rowsaffected()求受影響的行數。rowsaffected返回update, insert, or delete影響的行數。不是每乙個資料庫和資料庫驅動可能支援這個。

lastinsertid()求插入的最後一行的id。

lastinsertid返回資料庫生成的最後乙個id。通常,這來自插入新行時的「自動遞增」列。不是所有資料庫都支援此功能。

result, e := db.exec("delete from person where name not like ?;", "%揚")

還是執行db.exec(),第乙個引數是delete語句。

檢視該操作是否執行成功。

成功!!!試一試吧!

result, e := db.exec("update person set name = ? where id = ?;", "大揚", 1)

成功執行!

來看一看結果吧!

現在可以看到資料更新成功。將id為1的資料的name項更新為」大揚「。

這裡兩個?,後面就要有兩個引數。

package main

​import (

"fmt"

//並不需要使用其api,只需要執行該包的init方法(載入mysql是驅動程式)

"github程式設計客棧.com/jmoiron/sqlx")​

type person struct

​func main()

fmt.println("查詢成功",ps)

}person結構體裡面的屬性對應資料庫裡面的字段。比如:

age int `db:"age"`

表示age對應表裡面的字段age。

type person struct

var ps person

因為查詢的結果可能為多條,所以使用person切片。然後將查詢結果放入ps中

提示:要使用ps的指標!

e := db.select(&ps, "select name,age,rmb from person where name like ?;", "%揚")

下面我們來看看查詢結果:

Go語言實現Valid Parentheses

write a function called that takes a string of parentheses,and determines if the order of the parentheses is valid.the function should return true if ...

go語言實現鍊錶

宣告結構體 宣告全域性變數,儲存頭結點 var head node var curr node 宣告節點型別 type node struct 建立頭結點 func createheadnode data string node 新增新節點 func addnode data string node...

Go語言實現走迷宮

package main import fmt os exec os time 定義全域性變數 var 定義變數儲存r當前位置 currentrow 1 currentcol 1 定義變數儲存迷宮出口位置 索引 endrow 1 endcol 5 func main 2.定義乙個函式列印地圖 pri...