package main
//mysql
import (
"bytes"
"database/sql"
"errors"
"strings"
_ "github.com/go-sql-driver/mysql"
)
var db *sql.DB //数据库 句柄
var errorG error //全局变量
func init() {
//"root:root@tcp(localhost:3306)/flask_sx_test?charset=utf8"
db, errorG = sql.Open("mysql", "root:root@tcp(localhost:3306)/flask_sx_test?charset=utf8")
if errorG != nil {
panic(errorG)
}
}
/*
功能: 查询
参数
tablename 表名
cond 选择条件
items 选择的字段名
返回值
...未定
*/
// Ex "select id,name from flask_sx_test.stu_test where id = 2"
func query(items []string, tablebname string, cond string) (row *sql.Rows, err error) {
strQuery := "select "
var buffer bytes.Buffer
buffer.WriteString(strQuery)
if items[0] == "*" {
buffer.WriteString(" * ")
} else {
for i, v := range items {
if i != len(items)-1 {
buffer.WriteString(v + ",")
} else {
buffer.WriteString(v)
}
}
}
buffer.WriteString(" from " + tablebname)
buffer.WriteString(" where " + cond)
stmt, err := db.Prepare(buffer.String())
if err != nil {
return nil, err
}
defer stmt.Close()
rows, err := stmt.Query()
if err != nil {
return nil, err
}
return rows, nil
}
/*
功能: 插入
参数:
tablename 表名
itemSlice
valueSlice //暂时为string
Ex. INSERT INTO stu_test (`name`,address) VALUES ("www", "bj")
*/
func insert(tablebname string, itemSlice []string, valueSlice []interface{}) (err error) {
if len(itemSlice) != len(valueSlice) {
return errors.New("dismatch of items with values")
}
var buff bytes.Buffer
buff.WriteString("insert into")
buff.WriteString(tablebname + " (")
buff.WriteString(strings.Join(itemSlice, ", "))
buff.WriteString(") values (")
//mysql 中 ?的数量
temp1 := []string{}
for index := 0; index < len(itemSlice); index++ {
temp1 = append(temp1, "?")
}
buff.WriteString(strings.Join(temp1, ", "))
buff.WriteString(" )")
//fmt.Println(buff.String())
stmt, err := db.Prepare(buff.String())
if err != nil {
return err
}
defer stmt.Close()
stmt.Exec(valueSlice...)
return
}
/*
功能:删除一行
参数
tablename 表名
cond: 筛选条件
values: 条件值
*/
func deleteRow(tablename string, cond []string, values []interface{}) (err error) {
var buff bytes.Buffer
buff.WriteString("delete from")
buff.WriteString(tablename)
buff.WriteString(" where (")
//buff.WriteString(cond)
tmp := make([]string, len(cond))
for i, v := range cond {
tmp[i] = v + "=?"
}
buff.WriteString(strings.Join(tmp, " AND "))
buff.WriteString(")")
stmt, err := db.Prepare(buff.String())
if err != nil {
return err
}
stmt.Exec(values...)
}
func main() {
s1 := []string{" name ", " address "}
// res, _ := query(s1, " flask_sx_test.stu_test ", " id = 2 ")
// var id int
// var name string
// for res.Next() {
// res.Columns()
// res.Scan(&id, &name)
// fmt.Println(id, name)
// }
s2 := []string{"byw", " american"}
s3 := make([]interface{}, len(s2))
for i, v := range s2 {
s3[i] = v
}
insert(" flask_sx_test.stu_test", s1, s3)
}
go操作mysql数据库
最新推荐文章于 2024-11-17 08:35:13 发布