mysql和oracle的增删改查
导入相关的包
import (
"database/sql" //数据库操作
"fmt" //输出
_ "github.com/go-sql-driver/mysql" //mysql驱动
_ "github.com/mattn/go-oci8" //oracle驱动
)
初始化数据库连接
/*基础代码*/
func initIni() {
// 建议从配置文件中获取
ip = "127.0.0.1"
port = "3306"
username = "root"
password = "123456"
database = "test01"
// ip = "127.0.0.1"
// port = "1521"
// username = "root"
// password = "123456"
// database = "orcl"
}
func InitDB() (db *sql.DB, err error) {
initIni()
//连接字符串
mysqldsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", username, password, ip, port, database)
// oracledsn := fmt.Sprintf("%s/%s@%s:%s/%s", username, password, ip, port, database)
//Open只会验证dsb的格式是否正确,不会验证是否连接成功,同理,密码是否正确也不知道
db, err = sql.Open("mysql", mysqldsn)
// db, err = sql.Open("oci8", oracledsn)
if err != nil {
fmt.Println(`验证格式失败`, mysqldsn, err)
return nil, err
}
// 此时尝试连接数据库,会判断用户,密码,ip地址,端口是否正确
err = db.Ping()
if err != nil {
fmt.Println(`连接数据库失败`, err)
return nil, err
}
return db, nil
}
操作_新增
func Insertdb(db *sql.DB, sqlStr string, args ...interface{}) (int64, error) {
// stmt, err := db.Prepare("insert userinfo set username=?,departname=?,created=?,password=?,uid=?")
stmt, err := db.Prepare(sqlStr)
res, err := stmt.Exec(args...)
//LastInsertId()这个函数需要和AUTO_INCREMENT 属性一起使用
id, err := res.LastInsertId()
fmt.Println("插入数据成功:", id)
return id, err
}
操作_查询
func Querydb(db *sql.DB, sqlStr string, args ...interface{}) ([]map[string]string, error) {
rows, err := db.Query(sqlStr, args...)
if err != nil {
return nil, err
}
//函数结束释放链接
defer rows.Close()
//读出查询出的列字段名
cols, _ := rows.Columns()
//values是每个列的值,这里获取到byte里
values := make([][]byte, len(cols))
//query.Scan的参数,因为每次查询出来的列是不定长的,用len(cols)定住当次查询的长度
scans := make([]interface{}, len(cols))
//让每一行数据都填充到[][]byte里面
for i := range values {
scans[i] = &values[i]
}
results := make([]map[string]string, 0)
//多行遍历
for rows.Next() {
err := rows.Scan(scans...)
if err != nil {
return nil, err
}
row := make(map[string]string, 10)
//一行多字段遍历,
for k, v := range values { //每行数据是放在values里面,现在把它挪到row里
key := cols[k]
row[key] = string(v)
}
results = append(results, row)
}
return results, nil
}
操作_修改
func UpdateDB(db *sql.DB, sqlStr string, args ...interface{}) (int64, error) {
stmt, err := db.Prepare(sqlStr)
res, err := stmt.Exec(args...)
fmt.Println(err)
affect, err := res.RowsAffected() //修改行数
fmt.Println("更新数据:", affect)
return affect, err
}
操作_删除
func DeleteDB(db *sql.DB, sqlStr string, args ...interface{}) (int64, error) {
stmt, err := db.Prepare(sqlStr)
res, err := stmt.Exec(args...)
affect, err := res.RowsAffected() //删除行数
fmt.Println("删除数据:", affect)
return affect, err
}
测试
func main() {
//Go中可以抛出一个panic的异常,然后在defer中通过recover捕获这个异常,然后正常处理。
defer func() { // 必须要先声明defer,否则不能捕获到panic异常
fmt.Println("d")
if err := recover(); err != nil {
fmt.Println(err) // 这里的err其实就是panic传入的内容,55
}
fmt.Println("e")
}()
//建立数据库连接
db, err := InitDB()
if err != nil {
fmt.Println("错误:", err)
}
//函数结束释放链接
defer db.Close()
//新增
iStr := `INSERT INTO test(uid, email,phone) VALUES (?, ?, ?);`
pStr1 := `3`
pStr2 := `32`
iresult, err2 := Insertdb(db, iStr, pStr1, pStr2, `321`)
if err2 != nil {
fmt.Print(`新增条数:`)
fmt.Println(iresult)
}
//查询
qStr := `select email,phone from test where uid = ? and phone = ?`
pStr3 := `3`
pStr4 := `321`
qresult, err1 := Querydb(db, qStr, pStr3, pStr4)
if err1 != nil {
} else {
lresult := len(qresult)
fmt.Println(lresult)
//多行遍历
for _, value := range qresult {
//一行多字段遍历,
for k, v := range value {
fmt.Println(`列名:` + k + ` 值:` + v)
}
fmt.Println(`另起一行:`)
}
}
//修改
uString := `update test set phone = ? where uid = ? and email = ?`
pStr5 := `123`
UpdateDB(db, uString, pStr5, pStr1, pStr2)
//删除
dStr := "Delete from test where uid = ? and phone = ?"
pStr7 := `3`
dresult, err3 := DeleteDB(db, dStr, pStr7, pStr5)
if err3 != nil {
fmt.Print(`删除条数:`)
fmt.Println(dresult)
}
}