go 操作mysql 增刪改查

2021-07-04 03:15:31 字數 1742 閱讀 7830

go中支援mysql的驅動目前比較多,有如下幾種,有些是支援database/sql標準,而有些是採用了自己的實現介面,常用的有如下幾種:

接下來的例子我主要以第乙個驅動為例(我目前專案中也是採用它來驅動),也推薦大家採用它,主要理由:

接下來的幾個小節裡面我們都將採用同乙個資料庫表結構:資料庫test,使用者表userinfo,關聯使用者資訊表userdetail。

create table `userinfo` (

`uid` int(10) not null auto_increment,

`username` varchar(64) null default null,

`departname` varchar(64) null default null,

`created` date null default null,

primary key (`uid`)

)create table `userdetail` (

`uid` int(10) not null default '0',

`intro` text null,

`profile` text null,

primary key (`uid`)

)

如下示例將示範如何使用database/sql介面對資料庫表進行增刪改查操作
package main

//刪除資料

stmt, err = db.prepare("delete from userinfo where uid=?")

checkerr(err)

res, err = stmt.exec(id)

checkerr(err)

affect, err = res.rowsaffected()

checkerr(err)

fmt.println(affect)

db.close()

}func checkerr(err error)

}

通過上面的**我們可以看出,go操作mysql資料庫是很方便的。

關鍵的幾個函式我解釋一下:

sql.open()函式用來開啟乙個註冊過的資料庫驅動,go-sql-driver中註冊了mysql這個資料庫驅動,第二個引數是dsn(data source name),它是go-sql-driver定義的一些資料庫鏈結和配置資訊。它支援如下格式:

user@unix(/path/to/socket)/dbname?charset=utf8

user:password@tcp(localhost:5555)/dbname?charset=utf8

user:password@/dbname

user:password@tcp([de:ad:be:ef::ca:fe]:80)/dbname

db.prepare()函式用來返回準備要執行的sql操作,然後返回準備完畢的執行狀態。

db.query()函式用來直接執行sql返回rows結果。

stmt.exec()函式用來執行stmt準備好的sql語句

我們可以看到我們傳入的引數都是=?對應的資料,這樣做的方式可以一定程度上防止sql注入。

go操作操作mysql(增刪改查)

go中支援mysql的驅動目前比較多,有如下幾種,有些是支援database sql標準,而有些是採用了自己的實現介面,常用的有如下幾種 支援database sql,全部採用go寫。支援database sql,也支援自定義的介面,全部採用go寫。不支援database sql,自定義介面,全部採...

MySQL 增刪改查操作

toc 登入資料庫 mysql u root p123456 建立資料庫 creat database test 檢視所有資料庫 show databases 檢視資料庫中所有的資料表 show tables 選中資料庫 usedatabases 建立資料表 create table pet nam...

MySQL增刪改查操作

增刪改查操作 查詢表中的所有的記錄 select from 表名 xs 建立資料庫 create database if not exists xsgl 8.2建立表 cerate table if not exists 判斷是否存在 表名 xsb 8.3刪除 drop database if ex...