Browse Source

chain.go增加直接查询数据方法Get(),List()

master v0.6.0
guzeng 3 years ago
parent
commit
302482fa54
4 changed files with 330 additions and 10 deletions
  1. +26
    -0
      chain.go
  2. +4
    -2
      chain_test.go
  3. +275
    -0
      db.go
  4. +25
    -8
      db_test.go

+ 26
- 0
chain.go View File

@ -402,6 +402,19 @@ func (this *Query) Select() ([]map[string]string, error) {
return StmtForQueryList(this.stmt, this.value) return StmtForQueryList(this.stmt, this.value)
} }
/**
* 执行查询多条数据
* return row error
* 2022/01/05
*/
func (this *Query) List() ([]map[string]string, error) {
_, rows, err := FetchRows(this.dbname, this.table, this.alias, this.title, this.join,
this.where, this.where_or, this.value, this.orderby, this.page, this.page_size, this.debug)
return rows, err
}
/** /**
* 执行查询一条数据 * 执行查询一条数据
* return row error * return row error
@ -420,6 +433,19 @@ func (this *Query) Find() (map[string]string, error) {
return StmtForQueryRow(this.stmt, this.value) return StmtForQueryRow(this.stmt, this.value)
} }
/**
* 执行查询一条数据
* return row error
* 2022/01/05
*/
func (this *Query) Get() (map[string]string, error) {
_, row, err := GetRow(this.dbname, this.table, this.alias, this.title, this.join,
this.where, this.where_or, this.value, this.orderby, this.debug)
return row, err
}
/** /**
* 执行更新 * 执行更新
* return is_updated error * return is_updated error


+ 4
- 2
chain_test.go View File

@ -5,9 +5,11 @@ import (
) )
func Test_Chain(t *testing.T) { func Test_Chain(t *testing.T) {
Connect("127.0.0.1", "root", "123456", "test1_tetele_com", "3306")
Connect("127.0.0.1", "root", "123456", "shop", "3306")
ret, err := new(Query).Db("test1_tetele_com").Table("ttl_user").Title("id,username").WhereOr("id =?").WhereOr("id = ?").Value(2).Value(4).Value(4).PageSize(4).Select()
ret, err := new(Query).Db("shop").Table("ttl_order_product").Alias("op").
Join([]string{"ttl_product as p", "op.product_id=p.id"}).
Title("op.id,op.order_price,p.thumb").WhereOr("op.id =?").WhereOr("op.id = ?").Value(63).Value(64).Debug(true).List()
t.Log(len(ret)) t.Log(len(ret))
t.Log(ret) t.Log(ret)


+ 275
- 0
db.go View File

@ -3,6 +3,7 @@ package dbquery
import ( import (
"database/sql" "database/sql"
"log" "log"
"strconv"
"errors" "errors"
"strings" "strings"
@ -277,6 +278,280 @@ func GetData(dbName, table string, title string, where map[string]string, limit
return count, info, nil return count, info, nil
} }
/**
* 查找一条记录
* @param dbName 数据表名
* @param title 查询字段名
*/
func GetRow(dbName, table_name, alias string, titles string, join [][]string, where, where_or []string, valueList []interface{}, orderby string, debug bool) (int, map[string]string, error) {
var count int = 0
info := make(map[string]string)
if dbName == "" && table_name == "" {
return count, info, errors.New("没有数据表")
}
table := getTableName(dbName, table_name)
var sql_str, title string
if titles != "" {
title = titles
} else {
title = "*"
}
sql_str = helper.StringJoin("/*slave*/ select ", title)
if alias != "" {
table = helper.StringJoin(table, " as ", alias)
}
sql_str = helper.StringJoin(sql_str, " from ", table)
if len(join) > 0 {
for _, joinitem := range join {
if len(joinitem) < 2 {
continue
}
if len(joinitem) == 3 {
sql_str = helper.StringJoin(sql_str, " ", joinitem[2], " join ", getTableName(dbName, joinitem[0]), " on ", joinitem[1])
} else { //默认左连接
sql_str = helper.StringJoin(sql_str, " left join ", getTableName(dbName, joinitem[0]), " on ", joinitem[1])
}
}
}
if len(where) > 0 || len(where_or) > 0 {
sql_str = helper.StringJoin(sql_str, " where ")
}
if len(where) > 0 {
sql_str = helper.StringJoin(sql_str, " (", strings.Join(where, " and "), " ) ")
}
if len(where_or) > 0 {
if len(where) > 0 {
sql_str = helper.StringJoin(sql_str, " or ", strings.Join(where_or, " or "))
} else {
sql_str = helper.StringJoin(sql_str, strings.Join(where_or, " or "))
}
}
if orderby != "" {
sql_str = helper.StringJoin(sql_str, " order by ", orderby)
}
if debug {
log.Println("query sql:", sql_str, valueList)
}
condition_len := 0 //所有条件数
for _, ch2 := range sql_str {
if string(ch2) == "?" {
condition_len++
}
}
if condition_len != len(valueList) {
return 0, nil, errors.New("参数错误,条件值错误")
}
var rows *sql.Rows
var err error
var queryNum int = 0
for queryNum < 2 { //如发生错误,继续查询2次,防止数据库连接断开问题
rows, err = DB.Query(sql_str, valueList...)
if err == nil {
break
} else {
log.Println(err)
time.Sleep(time.Millisecond * 500)
}
queryNum++
}
if err != nil {
rows.Close()
return count, info, err
}
columns, _ := rows.Columns()
scanArgs := make([]interface{}, len(columns))
values := make([]interface{}, len(columns))
for i := range values {
scanArgs[i] = &values[i]
}
var index string
var rowerr error
for rows.Next() {
rowerr = rows.Scan(scanArgs...)
if rowerr == nil {
for i, col := range values {
if col != nil {
index = helper.StrFirstToUpper(columns[i])
info[index] = helper.ToString(col)
}
}
count++
} else {
log.Println("ERROR", rowerr)
}
}
rows.Close()
if rowerr != nil {
return count, info, rowerr
}
return count, info, nil
}
/**
* 查找多条记录
* @param dbName 数据表名
* @param title 查询字段名
*/
func FetchRows(dbName, table_name, alias string, titles string, join [][]string, where, where_or []string, valueList []interface{}, orderby string, page int, page_size int, debug bool) (int, []map[string]string, error) {
var count int = 0
list := make([]map[string]string, 0)
if dbName == "" && table_name == "" {
return count, list, errors.New("没有数据表")
}
table := getTableName(dbName, table_name)
var sql_str, title string
if titles != "" {
title = titles
} else {
title = "*"
}
sql_str = helper.StringJoin("/*slave*/ select ", title)
if alias != "" {
table = helper.StringJoin(table, " as ", alias)
}
sql_str = helper.StringJoin(sql_str, " from ", table)
if len(join) > 0 {
for _, joinitem := range join {
if len(joinitem) < 2 {
continue
}
if len(joinitem) == 3 {
sql_str = helper.StringJoin(sql_str, " ", joinitem[2], " join ", getTableName(dbName, joinitem[0]), " on ", joinitem[1])
} else { //默认左连接
sql_str = helper.StringJoin(sql_str, " left join ", getTableName(dbName, joinitem[0]), " on ", joinitem[1])
}
}
}
if len(where) > 0 || len(where_or) > 0 {
sql_str = helper.StringJoin(sql_str, " where ")
}
if len(where) > 0 {
sql_str = helper.StringJoin(sql_str, " (", strings.Join(where, " and "), " ) ")
}
if len(where_or) > 0 {
if len(where) > 0 {
sql_str = helper.StringJoin(sql_str, " or ", strings.Join(where_or, " or "))
} else {
sql_str = helper.StringJoin(sql_str, strings.Join(where_or, " or "))
}
}
if orderby != "" {
sql_str = helper.StringJoin(sql_str, " order by ", orderby)
}
if page > 0 || page_size > 0 {
if page < 1 {
page = 1
}
if page_size < 1 {
page_size = 10
}
from := strconv.Itoa((page - 1) * page_size)
offset := strconv.Itoa(page_size)
if from != "" && offset != "" {
sql_str = helper.StringJoin(sql_str, " limit ", from, " , ", offset)
}
}
if debug {
log.Println("query sql:", sql_str, valueList)
}
condition_len := 0 //所有条件数
for _, ch2 := range sql_str {
if string(ch2) == "?" {
condition_len++
}
}
if condition_len != len(valueList) {
return 0, list, errors.New("参数错误,条件值错误")
}
var rows *sql.Rows
var err error
var queryNum int = 0
for queryNum < 2 { //如发生错误,继续查询2次,防止数据库连接断开问题
rows, err = DB.Query(sql_str, valueList...)
if err == nil {
break
} else {
log.Println(err)
time.Sleep(time.Millisecond * 500)
}
queryNum++
}
if err != nil {
rows.Close()
return 0, list, err
}
columns, _ := rows.Columns()
scanArgs := make([]interface{}, len(columns))
values := make([]interface{}, len(columns))
for i := range values {
scanArgs[i] = &values[i]
}
var index string
var rowerr error
var info map[string]string
for rows.Next() {
rowerr = rows.Scan(scanArgs...)
info = make(map[string]string)
if rowerr == nil {
for i, col := range values {
if col != nil {
index = helper.StrFirstToUpper(columns[i])
info[index] = helper.ToString(col)
}
}
count++
} else {
log.Println("ERROR", rowerr)
}
if len(info) > 0 {
list = append(list, info)
}
}
rows.Close()
return count, list, nil
}
func GetInfo(dbName, table string, title string, where map[string]string) (map[string]string, error) { func GetInfo(dbName, table string, title string, where map[string]string) (map[string]string, error) {
count, info, gzErr := GetData(dbName, table, title, where, nil) count, info, gzErr := GetData(dbName, table, title, where, nil)


+ 25
- 8
db_test.go View File

@ -7,12 +7,13 @@ import (
func Test_Connet(t *testing.T) { func Test_Connet(t *testing.T) {
//go func() { //go func() {
for i := 0; i < 100; i++ {
dbhost := "106.52.13.101"
for i := 0; i < 1; i++ {
dbhost := "localhost"
dbname := "shop" dbname := "shop"
dbusername := "yueheng_read"
dbpassword := "yhmast@4&345Ms"
dbport := "13306"
dbusername := "tetele"
dbpassword := "fly123456"
dbport := "3306"
table := "ttl_order_product"
err := Connect(dbhost, dbusername, dbpassword, dbname, dbport) err := Connect(dbhost, dbusername, dbpassword, dbname, dbport)
if err != nil { if err != nil {
@ -21,10 +22,26 @@ func Test_Connet(t *testing.T) {
//_,err = new(Query).Db(dbname).Table("ttl_user").Where("id > 0").Select() //_,err = new(Query).Db(dbname).Table("ttl_user").Where("id > 0").Select()
_, err = new(Query).Db(dbname).Table("ttl_news").
Datas([]string{"title=?", "content=?"}).
Values([]interface{}{"aaaaaaaaa", "bbbbbb"}).Create()
// _, err = new(Query).Db(dbname).Table("ttl_news").
// Datas([]string{"title=?", "content=?"}).
// Values([]interface{}{"aaaaaaaaa", "bbbbbb"}).Create()
title := "op.id,op.sn,op.order_price"
alias := "op"
join := [][]string{}
join = append(join, []string{"ttl_product as p", "op.product_id=p.id"})
where := []string{}
where_or := []string{}
valueList := []interface{}{}
orderby := "id desc"
debug := true
// count, row, err := GetRow(dbname, table, alias, title, join, where, where_or, valueList, orderby, debug)
count, row, err := FetchRows(dbname, table, alias, title, join, where, where_or, valueList, orderby, 1, 10, debug)
log.Println(count)
log.Println(row)
log.Println(err)
if err != nil { if err != nil {
log.Println(err.Error()) log.Println(err.Error())
} }


Loading…
Cancel
Save