数据库操作
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1049 lines
22 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
1 year ago
1 year ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. package dbquery
  2. import (
  3. "database/sql"
  4. "log"
  5. "strconv"
  6. "errors"
  7. "strings"
  8. "time"
  9. "git.tetele.net/tgo/helper"
  10. _ "github.com/go-sql-driver/mysql"
  11. )
  12. /**
  13. * 创建数据
  14. */
  15. func Insert(dbName, table string, data map[string]string) (int64, error) {
  16. var insertId int64
  17. var err error
  18. if dbName == "" && table == "" {
  19. return insertId, errors.New("没有数据表")
  20. }
  21. if strings.Contains(table, "select ") {
  22. dbName = table
  23. } else {
  24. dbName = getTableName(dbName, table)
  25. }
  26. if len(data) < 1 {
  27. return insertId, errors.New("没有要写入的数据")
  28. }
  29. keyList := make([]string, len(data))
  30. keyStr := make([]string, len(data))
  31. valueList := make([]interface{}, len(data))
  32. var i int = 0
  33. for key, value := range data {
  34. keyList[i] = key
  35. keyStr[i] = "?"
  36. valueList[i] = value
  37. i++
  38. }
  39. result, err := DB.Exec("insert into "+dbName+" ("+strings.Join(keyList, ",")+") value("+strings.Join(keyStr, ",")+")", valueList...)
  40. if err != nil {
  41. log.Println("ERROR|插入", dbName, "数据失败,", err)
  42. return insertId, err
  43. } else {
  44. insertId, _ = result.LastInsertId()
  45. time.Sleep(time.Second * 2)
  46. return insertId, nil
  47. }
  48. }
  49. /**
  50. * 修改数据
  51. */
  52. func Update(dbName, table string, data map[string]string, where map[string]string) (int64, error) {
  53. var rowsAffected int64
  54. var err error
  55. if dbName == "" && table == "" {
  56. return rowsAffected, errors.New("没有数据表")
  57. }
  58. if strings.Contains(table, "select ") {
  59. dbName = table
  60. } else {
  61. dbName = getTableName(dbName, table)
  62. }
  63. if len(data) < 1 {
  64. return rowsAffected, errors.New("同有更新的数据")
  65. }
  66. if len(where) < 1 {
  67. return rowsAffected, errors.New("没有更新条件")
  68. }
  69. keyList := make([]string, len(data))
  70. valueList := make([]interface{}, len(data), len(data)+len(where))
  71. whereStr := make([]string, len(where))
  72. var i int = 0
  73. empty := false
  74. for key, value := range data {
  75. keyList[i] = key + "=?"
  76. valueList[i] = value
  77. i++
  78. }
  79. i = 0
  80. for key, value := range where {
  81. if value == "" {
  82. empty = true
  83. break
  84. }
  85. whereStr[i] = key + "=?"
  86. valueList = append(valueList, value)
  87. i++
  88. }
  89. if empty {
  90. log.Println("ERROR|修改数据表", dbName, "时条件中有空数据,条件:", where, "数据:", data)
  91. return rowsAffected, errors.New("条件中有空数据")
  92. }
  93. result, err := DB.Exec("update "+dbName+" set "+strings.Join(keyList, " , ")+" where "+strings.Join(whereStr, " and "), valueList...)
  94. if err != nil {
  95. log.Println("ERROR|修改", dbName, "数据失败,", err)
  96. return rowsAffected, err
  97. } else {
  98. rowsAffected, _ = result.RowsAffected()
  99. return rowsAffected, nil
  100. }
  101. }
  102. /**
  103. * 删除数据
  104. * @param count 删除数量
  105. */
  106. func Delete(dbName, table string, data map[string]string, del_count ...string) (int64, error) {
  107. var count int64
  108. var err error
  109. if dbName == "" && table == "" {
  110. return count, errors.New("没有数据表")
  111. }
  112. if strings.Contains(table, "select ") {
  113. dbName = table
  114. } else {
  115. dbName = getTableName(dbName, table)
  116. }
  117. if len(data) < 1 {
  118. return count, errors.New("没有要删除的数据")
  119. }
  120. keyList := make([]string, len(data))
  121. valueList := make([]interface{}, len(data))
  122. var i int = 0
  123. empty := false
  124. for key, value := range data {
  125. if value == "" {
  126. empty = true
  127. break
  128. }
  129. keyList[i] = key + "=?"
  130. valueList[i] = value
  131. i++
  132. }
  133. if empty {
  134. log.Println("ERROR|删除数据表", dbName, "时条件中有空数据,条件:", data)
  135. return count, errors.New("条件中有空数据")
  136. }
  137. var limitStr string = ""
  138. if len(del_count) > 0 {
  139. limitStr = " limit " + del_count[0]
  140. }
  141. result, err := DB.Exec("delete from "+dbName+" where "+strings.Join(keyList, " and ")+limitStr, valueList...)
  142. if err != nil {
  143. log.Println("ERROR|删除", dbName, "数据失败,", err)
  144. return count, err
  145. } else {
  146. count, _ = result.RowsAffected()
  147. return count, nil
  148. }
  149. }
  150. /**
  151. * 查找一条记录
  152. * @param dbName 数据表名
  153. * @param title 查询字段名
  154. */
  155. func GetData(dbName, table string, title string, where map[string]string, limit map[string]string) (int, map[string]string, error) {
  156. var count int = 0
  157. info := make(map[string]string)
  158. if dbName == "" && table == "" {
  159. return count, info, errors.New("没有数据表")
  160. }
  161. dbName = getTableName(dbName, table)
  162. if len(title) < 1 {
  163. return count, info, errors.New("没有指定查询内容")
  164. }
  165. var limitStr string = ""
  166. if limit != nil && len(limit) > 0 {
  167. var from string = "0" //开始
  168. if _, ok := limit["order"]; ok {
  169. limitStr += " order by " + limit["order"]
  170. }
  171. if _, ok := limit["from"]; ok {
  172. from = limit["from"]
  173. }
  174. limitStr += " limit " + from + ",1"
  175. } else {
  176. limitStr = " limit 1"
  177. }
  178. if len(where) < 1 {
  179. return count, info, errors.New("Query condition is empty")
  180. }
  181. keyList := make([]string, len(where))
  182. valueList := make([]interface{}, len(where))
  183. var i int = 0
  184. empty := false
  185. for key, value := range where {
  186. if value == "" {
  187. empty = true
  188. break
  189. }
  190. keyList[i] = key + " = ? "
  191. valueList[i] = value
  192. i++
  193. }
  194. if empty {
  195. return count, info, errors.New("Query condition is empty")
  196. }
  197. var rows *sql.Rows
  198. var err error
  199. var queryNum int = 0
  200. for queryNum < 3 { //如发生错误,继续查询3次,防止数据库连接断开问题
  201. rows, err = DB.Query("SELECT "+title+" FROM "+dbName+" where "+strings.Join(keyList, " and ")+" "+limitStr, valueList...)
  202. if err == nil {
  203. break
  204. } else {
  205. log.Println("ERROR", "Query from", dbName, "failed,", err, "| SELECT "+title+" FROM "+dbName+" where "+strings.Join(keyList, " and ")+" "+limitStr)
  206. time.Sleep(time.Millisecond * 500)
  207. }
  208. queryNum++
  209. }
  210. defer rows.Close()
  211. if err != nil {
  212. return count, info, err
  213. }
  214. columns, _ := rows.Columns()
  215. scanArgs := make([]interface{}, len(columns))
  216. values := make([]interface{}, len(columns))
  217. for i := range values {
  218. scanArgs[i] = &values[i]
  219. }
  220. var index string
  221. var rowerr error
  222. for rows.Next() {
  223. rowerr = rows.Scan(scanArgs...)
  224. if rowerr == nil {
  225. for i, col := range values {
  226. if col != nil {
  227. index = helper.StrFirstToUpper(columns[i])
  228. info[index] = helper.ToString(col)
  229. }
  230. }
  231. count++
  232. } else {
  233. log.Println("ERROR", "rows scan error", rowerr, dbName, keyList, valueList)
  234. }
  235. }
  236. if rowerr != nil {
  237. return count, info, rowerr
  238. }
  239. return count, info, nil
  240. }
  241. /**
  242. * 查找一条记录
  243. * @param dbName 数据表名
  244. * @param title 查询字段名
  245. */
  246. func GetRow(dbName, table_name, alias string, titles string, with, join [][]string, where, where_or []string, valueList []interface{}, orderby, groupby, having string, debug bool) (int, map[string]string, error) {
  247. var count int = 0
  248. info := make(map[string]string)
  249. if dbName == "" && table_name == "" {
  250. return count, info, errors.New("没有数据表")
  251. }
  252. table := ""
  253. withSql := ""
  254. if len(with) > 0 {
  255. var builder strings.Builder
  256. builder.Reset()
  257. builder.WriteString("WITH ")
  258. boo := false
  259. for k, v := range with {
  260. if len(v) < 2 {
  261. continue
  262. }
  263. if k != 0 {
  264. builder.WriteString(", ")
  265. }
  266. builder.WriteString(v[1])
  267. builder.WriteString(" as (")
  268. builder.WriteString(v[0])
  269. builder.WriteString(")")
  270. boo = true
  271. }
  272. if boo {
  273. builder.WriteString(" ")
  274. withSql = builder.String()
  275. }
  276. }
  277. if withSql != "" || strings.Contains(table_name, "select ") || strings.HasPrefix(table, "(") {
  278. table = table_name
  279. } else {
  280. table = getTableName(dbName, table_name)
  281. }
  282. var sql_str, title string
  283. if titles != "" {
  284. title = titles
  285. } else {
  286. title = "*"
  287. }
  288. if DB_PROVIDER == "TencentDB" {
  289. sql_str = helper.StringJoin("/*slave*/ ", withSql, " select ", title)
  290. } else {
  291. sql_str = helper.StringJoin(withSql, "select ", title)
  292. }
  293. if alias != "" {
  294. table = helper.StringJoin(table, " as ", alias)
  295. }
  296. sql_str = helper.StringJoin(sql_str, " from ", table)
  297. if len(join) > 0 {
  298. var builder strings.Builder
  299. builder.Reset()
  300. for _, joinitem := range join {
  301. if len(joinitem) < 2 {
  302. continue
  303. }
  304. builder.WriteString(sql_str)
  305. builder.WriteString(" ")
  306. if len(joinitem) >= 3 {
  307. builder.WriteString(joinitem[2])
  308. } else {
  309. builder.WriteString("left")
  310. }
  311. builder.WriteString(" join ")
  312. if withSql != "" || strings.Contains(joinitem[0], "select ") || strings.HasPrefix(joinitem[0], "(") || len(joinitem) > 4 {
  313. builder.WriteString(joinitem[0])
  314. } else {
  315. builder.WriteString(getTableName(dbName, joinitem[0]))
  316. }
  317. builder.WriteString(" on ")
  318. builder.WriteString(joinitem[1])
  319. }
  320. if builder.Len() > 0 {
  321. sql_str = builder.String()
  322. }
  323. }
  324. if len(where) > 0 || len(where_or) > 0 {
  325. sql_str = helper.StringJoin(sql_str, " where ")
  326. }
  327. if len(where) > 0 {
  328. sql_str = helper.StringJoin(sql_str, " (", strings.Join(where, " and "), " ) ")
  329. }
  330. if len(where_or) > 0 {
  331. if len(where) > 0 {
  332. sql_str = helper.StringJoin(sql_str, " or ", strings.Join(where_or, " or "))
  333. } else {
  334. sql_str = helper.StringJoin(sql_str, strings.Join(where_or, " or "))
  335. }
  336. }
  337. if groupby != "" {
  338. sql_str = helper.StringJoin(sql_str, " group by ", groupby)
  339. }
  340. if having != "" {
  341. sql_str = helper.StringJoin(sql_str, " having ", having)
  342. }
  343. if orderby != "" {
  344. sql_str = helper.StringJoin(sql_str, " order by ", orderby)
  345. }
  346. if debug {
  347. log.Println("query sql:", sql_str, valueList)
  348. }
  349. condition_len := 0 //所有条件数
  350. for _, ch2 := range sql_str {
  351. if string(ch2) == "?" {
  352. condition_len++
  353. }
  354. }
  355. if condition_len != len(valueList) {
  356. return 0, nil, errors.New("参数错误,条件值错误")
  357. }
  358. var rows *sql.Rows
  359. var err error
  360. var queryNum int = 0
  361. sql_str = helper.StringJoin(sql_str, " limit 1")
  362. var db *sql.DB
  363. if SLAVER_DB != nil {
  364. db = SLAVER_DB
  365. } else {
  366. db = DB
  367. }
  368. for queryNum < 2 { //如发生错误,继续查询2次,防止数据库连接断开问题
  369. rows, err = db.Query(sql_str, valueList...)
  370. if err == nil {
  371. break
  372. } else {
  373. log.Println(err)
  374. time.Sleep(time.Millisecond * 500)
  375. }
  376. queryNum++
  377. }
  378. if err != nil {
  379. log.Println("DB error:", err)
  380. rows.Close()
  381. return count, info, err
  382. }
  383. columns, _ := rows.Columns()
  384. scanArgs := make([]interface{}, len(columns))
  385. values := make([]interface{}, len(columns))
  386. for i := range values {
  387. scanArgs[i] = &values[i]
  388. }
  389. var index string
  390. var rowerr error
  391. for rows.Next() {
  392. rowerr = rows.Scan(scanArgs...)
  393. if rowerr == nil {
  394. for i, col := range values {
  395. if col != nil {
  396. index = helper.StrFirstToUpper(columns[i])
  397. info[index] = helper.ToString(col)
  398. }
  399. }
  400. count++
  401. } else {
  402. log.Println("ERROR", rowerr)
  403. }
  404. }
  405. rows.Close()
  406. if rowerr != nil {
  407. log.Println("DB row error:", rowerr)
  408. return count, info, rowerr
  409. }
  410. return count, info, nil
  411. }
  412. /**
  413. * 查找多条记录
  414. * @param dbName 数据表名
  415. * @param title 查询字段名
  416. */
  417. func FetchRows(dbName, table_name, alias string, titles string, with, join [][]string, where, where_or []string, valueList []interface{}, orderby, groupby, having string, page int, page_size int, debug bool) (int, []map[string]string, error) {
  418. var count int = 0
  419. list := make([]map[string]string, 0)
  420. if dbName == "" && table_name == "" {
  421. return count, list, errors.New("没有数据表")
  422. }
  423. table := ""
  424. withSql := ""
  425. if len(with) > 0 {
  426. var builder strings.Builder
  427. builder.Reset()
  428. builder.WriteString("WITH ")
  429. boo := false
  430. for k, v := range with {
  431. if len(v) < 2 {
  432. continue
  433. }
  434. if k != 0 {
  435. builder.WriteString(", ")
  436. }
  437. builder.WriteString(v[1])
  438. builder.WriteString(" as (")
  439. builder.WriteString(v[0])
  440. builder.WriteString(")")
  441. boo = true
  442. }
  443. if boo {
  444. builder.WriteString(" ")
  445. withSql = builder.String()
  446. }
  447. }
  448. if withSql != "" || strings.Contains(table_name, "select ") || strings.HasPrefix(table, "(") {
  449. table = table_name
  450. } else {
  451. table = getTableName(dbName, table_name)
  452. }
  453. var sql_str, title string
  454. if titles != "" {
  455. title = titles
  456. } else {
  457. title = "*"
  458. }
  459. if DB_PROVIDER == "TencentDB" {
  460. sql_str = helper.StringJoin("/*slave*/ ", withSql, " select ", title)
  461. } else {
  462. sql_str = helper.StringJoin(withSql, "select ", title)
  463. }
  464. if alias != "" {
  465. table = helper.StringJoin(table, " as ", alias)
  466. }
  467. sql_str = helper.StringJoin(sql_str, " from ", table)
  468. if len(join) > 0 {
  469. var builder strings.Builder
  470. builder.Reset()
  471. for _, joinitem := range join {
  472. if len(joinitem) < 2 {
  473. continue
  474. }
  475. builder.WriteString(sql_str)
  476. builder.WriteString(" ")
  477. if len(joinitem) >= 3 {
  478. builder.WriteString(joinitem[2])
  479. } else {
  480. builder.WriteString("left")
  481. }
  482. builder.WriteString(" join ")
  483. if withSql != "" || strings.Contains(joinitem[0], "select ") || strings.HasPrefix(joinitem[0], "(") || len(joinitem) >= 4 {
  484. builder.WriteString(joinitem[0])
  485. } else {
  486. builder.WriteString(getTableName(dbName, joinitem[0]))
  487. }
  488. builder.WriteString(" on ")
  489. builder.WriteString(joinitem[1])
  490. }
  491. if builder.Len() > 0 {
  492. sql_str = builder.String()
  493. }
  494. }
  495. if len(where) > 0 || len(where_or) > 0 {
  496. sql_str = helper.StringJoin(sql_str, " where ")
  497. }
  498. if len(where) > 0 {
  499. sql_str = helper.StringJoin(sql_str, " (", strings.Join(where, " and "), " ) ")
  500. }
  501. if len(where_or) > 0 {
  502. if len(where) > 0 {
  503. sql_str = helper.StringJoin(sql_str, " or ", strings.Join(where_or, " or "))
  504. } else {
  505. sql_str = helper.StringJoin(sql_str, strings.Join(where_or, " or "))
  506. }
  507. }
  508. if groupby != "" {
  509. sql_str = helper.StringJoin(sql_str, " group by ", groupby)
  510. }
  511. if having != "" {
  512. sql_str = helper.StringJoin(sql_str, " HAVING ", having)
  513. }
  514. if orderby != "" {
  515. sql_str = helper.StringJoin(sql_str, " order by ", orderby)
  516. }
  517. if page > 0 || page_size > 0 {
  518. if page < 1 {
  519. page = 1
  520. }
  521. if page_size < 1 {
  522. page_size = 10
  523. }
  524. from := strconv.Itoa((page - 1) * page_size)
  525. offset := strconv.Itoa(page_size)
  526. if from != "" && offset != "" {
  527. sql_str = helper.StringJoin(sql_str, " limit ", from, " , ", offset)
  528. }
  529. }
  530. if debug {
  531. log.Println("query sql:", sql_str, valueList)
  532. }
  533. condition_len := 0 //所有条件数
  534. for _, ch2 := range sql_str {
  535. if string(ch2) == "?" {
  536. condition_len++
  537. }
  538. }
  539. if condition_len != len(valueList) {
  540. return 0, list, errors.New("参数错误,条件值错误")
  541. }
  542. var db *sql.DB
  543. if SLAVER_DB != nil {
  544. db = SLAVER_DB
  545. } else {
  546. db = DB
  547. }
  548. var rows *sql.Rows
  549. var err error
  550. var queryNum int = 0
  551. for queryNum < 2 { //如发生错误,继续查询2次,防止数据库连接断开问题
  552. rows, err = db.Query(sql_str, valueList...)
  553. if err == nil {
  554. break
  555. } else {
  556. log.Println(err)
  557. time.Sleep(time.Millisecond * 500)
  558. }
  559. queryNum++
  560. }
  561. if err != nil {
  562. rows.Close()
  563. return 0, list, err
  564. }
  565. columns, _ := rows.Columns()
  566. scanArgs := make([]interface{}, len(columns))
  567. values := make([]interface{}, len(columns))
  568. for i := range values {
  569. scanArgs[i] = &values[i]
  570. }
  571. var index string
  572. var rowerr error
  573. var info map[string]string
  574. for rows.Next() {
  575. rowerr = rows.Scan(scanArgs...)
  576. info = make(map[string]string)
  577. if rowerr == nil {
  578. for i, col := range values {
  579. if col != nil {
  580. index = helper.StrFirstToUpper(columns[i])
  581. info[index] = helper.ToString(col)
  582. }
  583. }
  584. count++
  585. } else {
  586. log.Println("ERROR", rowerr)
  587. }
  588. if len(info) > 0 {
  589. list = append(list, info)
  590. }
  591. }
  592. rows.Close()
  593. return count, list, nil
  594. }
  595. func GetInfo(dbName, table string, title string, where map[string]string) (map[string]string, error) {
  596. count, info, gzErr := GetData(dbName, table, title, where, nil)
  597. if gzErr != nil {
  598. return info, gzErr
  599. } else {
  600. if count < 1 {
  601. return info, errors.New("No data")
  602. }
  603. return info, nil
  604. }
  605. }
  606. /**
  607. * 查询列表
  608. * 2018/04/19
  609. */
  610. func GetList(dbName, table string, title string, where map[string]string, limit map[string]string) ([]map[string]string, error) {
  611. var list []map[string]string
  612. if dbName == "" && table == "" {
  613. return list, errors.New("没有数据表")
  614. }
  615. if strings.Contains(table, "select ") {
  616. dbName = table
  617. } else {
  618. dbName = getTableName(dbName, table)
  619. }
  620. var rows *sql.Rows
  621. var err error
  622. var queryNum int = 0
  623. var limitStr string = ""
  624. if len(limit) > 0 {
  625. var offset string = "0" //偏移量,个数
  626. var from string = "" //开始
  627. if _, ok := limit["order"]; ok {
  628. limitStr += " order by " + limit["order"]
  629. }
  630. if _, ok := limit["offset"]; ok {
  631. offset = limit["offset"]
  632. }
  633. if _, ok := limit["from"]; ok {
  634. from = limit["from"]
  635. }
  636. if offset != "0" && from != "" {
  637. limitStr += " limit " + from + "," + offset
  638. }
  639. }
  640. if len(where) > 0 {
  641. valueList := make([]interface{}, len(where))
  642. whereStr := make([]string, len(where))
  643. i := 0
  644. var keys []string
  645. for key, value := range where {
  646. key = strings.Trim(key, " ")
  647. value = strings.Trim(value, " ")
  648. if value == "" || key == "" {
  649. continue
  650. // return list, errors.New("Query condition is empty")
  651. }
  652. if strings.Contains(key, " ") {
  653. //key中包含空格,判断是否不等于条件
  654. keys = strings.Split(key, " ")
  655. if helper.IsInStringArray(judg(), strings.Trim(keys[1], " ")) {
  656. whereStr[i] = strings.Trim(keys[0], " ") + " " + strings.Trim(keys[1], " ") + " ?"
  657. }
  658. } else {
  659. whereStr[i] = key + " = ?"
  660. valueList[i] = value
  661. }
  662. i++
  663. }
  664. if len(whereStr) == 0 || len(valueList) == 0 {
  665. return list, errors.New("Query condition is empty")
  666. }
  667. for queryNum < 5 { //如发生错误,继续查询5次,防止数据库连接断开问题
  668. rows, err = DB.Query("select "+title+" from "+dbName+" where "+strings.Join(whereStr, " and ")+" "+limitStr, valueList...)
  669. if err == nil {
  670. break
  671. } else {
  672. time.Sleep(time.Millisecond * 500)
  673. }
  674. queryNum++
  675. }
  676. } else {
  677. for queryNum < 5 { //如发生错误,继续查询5次,防止数据库连接断开问题
  678. rows, err = DB.Query("select " + title + " from " + dbName + " " + limitStr)
  679. if err == nil {
  680. break
  681. } else {
  682. time.Sleep(time.Millisecond * 500)
  683. }
  684. queryNum++
  685. }
  686. }
  687. if err != nil {
  688. return list, err
  689. }
  690. defer rows.Close()
  691. columns, _ := rows.Columns()
  692. scanArgs := make([]interface{}, len(columns))
  693. values := make([]interface{}, len(columns))
  694. for i := range values {
  695. scanArgs[i] = &values[i]
  696. }
  697. var record map[string]string
  698. var index string
  699. for rows.Next() {
  700. //将行数据保存到record字典
  701. err = rows.Scan(scanArgs...)
  702. record = make(map[string]string)
  703. for i, col := range values {
  704. if col != nil {
  705. index = helper.StrFirstToUpper(columns[i])
  706. record[index] = helper.ToString(col)
  707. }
  708. }
  709. list = append(list, record)
  710. }
  711. return list, nil
  712. }
  713. /**
  714. * 查询总数
  715. * 2018/04/19
  716. */
  717. func GetTotal(dbName, table string, args ...string) (total int) {
  718. if dbName == "" && table == "" {
  719. return
  720. }
  721. if strings.Contains(table, "select ") {
  722. dbName = table
  723. } else {
  724. dbName = getTableName(dbName, table)
  725. }
  726. var title string = "*"
  727. if len(args) > 0 {
  728. title = args[0]
  729. }
  730. var rows *sql.Rows
  731. var err error
  732. var queryNum int = 0
  733. for queryNum < 5 { //如发生错误,继续查询5次,防止数据库连接断开问题
  734. rows, err = DB.Query("select count(" + title + ") as count from " + dbName + " limit 1")
  735. if err == nil {
  736. break
  737. } else {
  738. time.Sleep(time.Millisecond * 500)
  739. }
  740. queryNum++
  741. }
  742. if err != nil {
  743. log.Println("ERROR|get", dbName, "total error", err)
  744. return
  745. }
  746. defer rows.Close()
  747. var count int
  748. for rows.Next() {
  749. //将行数据保存到record字典
  750. err = rows.Scan(&count)
  751. if err != nil {
  752. log.Println("ERROR|get", dbName, "total error", err)
  753. } else {
  754. total = count
  755. }
  756. }
  757. return
  758. }
  759. /**
  760. * 查询总数
  761. * 2020/06/04
  762. */
  763. func GetCount(dbName, table string, where map[string]string, args ...string) (total int) {
  764. if dbName == "" && table == "" {
  765. return
  766. }
  767. if strings.Contains(table, "select ") {
  768. dbName = table
  769. } else {
  770. dbName = getTableName(dbName, table)
  771. }
  772. var title string = "*"
  773. if len(title) > 0 {
  774. title = args[0]
  775. }
  776. var rows *sql.Rows
  777. var err error
  778. var queryNum int = 0
  779. if len(where) > 0 {
  780. valueList := make([]interface{}, len(where))
  781. whereStr := make([]string, len(where))
  782. i := 0
  783. var keys []string
  784. for key, value := range where {
  785. key = strings.Trim(key, " ")
  786. value = strings.Trim(value, " ")
  787. if value == "" || key == "" {
  788. continue
  789. // return list, errors.New("Query condition is empty")
  790. }
  791. if strings.Contains(key, " ") {
  792. //key中包含空格,判断是否不等于条件
  793. keys = strings.Split(key, " ")
  794. if helper.IsInStringArray(judg(), strings.Trim(keys[1], " ")) {
  795. whereStr[i] = strings.Trim(keys[0], " ") + " " + strings.Trim(keys[1], " ") + " ?"
  796. }
  797. } else {
  798. whereStr[i] = key + " = ?"
  799. valueList[i] = value
  800. }
  801. i++
  802. }
  803. for queryNum < 5 { //如发生错误,继续查询5次,防止数据库连接断开问题
  804. rows, err = DB.Query("select count("+title+") as count from "+dbName+" where "+strings.Join(whereStr, " and ")+" limit 1", valueList...)
  805. if err == nil {
  806. break
  807. } else {
  808. time.Sleep(time.Millisecond * 500)
  809. }
  810. queryNum++
  811. }
  812. } else {
  813. for queryNum < 5 { //如发生错误,继续查询5次,防止数据库连接断开问题
  814. rows, err = DB.Query("select count(" + title + ") as count from " + dbName + " limit 1")
  815. if err == nil {
  816. break
  817. } else {
  818. time.Sleep(time.Millisecond * 500)
  819. }
  820. queryNum++
  821. }
  822. }
  823. if err != nil {
  824. log.Println("ERROR|get", dbName, "count error", err)
  825. return
  826. }
  827. defer rows.Close()
  828. var count int
  829. for rows.Next() {
  830. //将行数据保存到record字典
  831. err = rows.Scan(&count)
  832. if err != nil {
  833. log.Println("ERROR|get", dbName, "count error", err)
  834. } else {
  835. total = count
  836. }
  837. }
  838. return
  839. }
  840. func DoQuery(args ...interface{}) ([]map[string]string, error) {
  841. var list []map[string]string
  842. if len(args) < 1 {
  843. return list, errors.New("Query condition is empty")
  844. }
  845. queryStr := helper.ToString(args[0])
  846. if queryStr == "" {
  847. return list, errors.New("Query condition is empty")
  848. }
  849. var rows *sql.Rows
  850. var err error
  851. var queryNum int = 0
  852. for queryNum < 3 { //如发生错误,继续查询5次,防止数据库连接断开问题
  853. if len(args) > 1 {
  854. rows, err = DB.Query(queryStr, args[1:]...) //strings.Join(args[1:], ",")
  855. if err != nil {
  856. log.Println("ERROR|DoQuery error:", err)
  857. }
  858. } else {
  859. rows, err = DB.Query(queryStr)
  860. if err != nil {
  861. log.Println("ERROR|DoQuery error:", err)
  862. }
  863. }
  864. if err == nil {
  865. break
  866. } else {
  867. time.Sleep(time.Millisecond * 500)
  868. }
  869. queryNum++
  870. }
  871. if err != nil {
  872. return list, err
  873. }
  874. defer rows.Close()
  875. columns, _ := rows.Columns()
  876. scanArgs := make([]interface{}, len(columns))
  877. values := make([]interface{}, len(columns))
  878. for i := range values {
  879. scanArgs[i] = &values[i]
  880. }
  881. var record map[string]string
  882. var index string
  883. for rows.Next() {
  884. //将行数据保存到record字典
  885. err = rows.Scan(scanArgs...)
  886. record = make(map[string]string)
  887. for i, col := range values {
  888. if col != nil {
  889. index = helper.StrFirstToUpper(columns[i])
  890. record[index] = helper.ToString(col)
  891. }
  892. }
  893. list = append(list, record)
  894. }
  895. return list, nil
  896. }