数据库操作
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.

1043 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. if strings.Contains(table_name, "select ") || strings.HasPrefix(table, "(") {
  254. table = table_name
  255. } else {
  256. table = getTableName(dbName, table_name)
  257. }
  258. var sql_str, title string
  259. if titles != "" {
  260. title = titles
  261. } else {
  262. title = "*"
  263. }
  264. withSql := ""
  265. if len(with) > 0 {
  266. var builder strings.Builder
  267. builder.WriteString("WITH ")
  268. boo := false
  269. for k, v := range with {
  270. if len(v) < 2 {
  271. continue
  272. }
  273. if k != 0 {
  274. builder.WriteString(", ")
  275. }
  276. builder.WriteString(v[1])
  277. builder.WriteString(" as (")
  278. builder.WriteString(v[0])
  279. builder.WriteString(")")
  280. boo = true
  281. }
  282. if boo {
  283. builder.WriteString(" ")
  284. withSql = builder.String()
  285. }
  286. }
  287. if DB_PROVIDER == "TencentDB" {
  288. sql_str = helper.StringJoin("/*slave*/ ", withSql, " select ", title)
  289. } else {
  290. sql_str = helper.StringJoin(withSql, "select ", title)
  291. }
  292. if alias != "" {
  293. table = helper.StringJoin(table, " as ", alias)
  294. }
  295. sql_str = helper.StringJoin(sql_str, " from ", table)
  296. if len(join) > 0 {
  297. var builder strings.Builder
  298. for _, joinitem := range join {
  299. if len(joinitem) < 2 {
  300. continue
  301. }
  302. builder.WriteString(sql_str)
  303. builder.WriteString(" ")
  304. if len(joinitem) >= 3 {
  305. builder.WriteString(joinitem[2])
  306. } else {
  307. builder.WriteString("left")
  308. }
  309. builder.WriteString(" join ")
  310. if strings.Contains(joinitem[0], "select ") || strings.HasPrefix(joinitem[0], "(") || len(joinitem) > 4 {
  311. builder.WriteString(joinitem[0])
  312. } else {
  313. builder.WriteString(getTableName(dbName, joinitem[0]))
  314. }
  315. builder.WriteString(" on ")
  316. builder.WriteString(joinitem[1])
  317. }
  318. if builder.Len() > 0 {
  319. sql_str = builder.String()
  320. }
  321. }
  322. if len(where) > 0 || len(where_or) > 0 {
  323. sql_str = helper.StringJoin(sql_str, " where ")
  324. }
  325. if len(where) > 0 {
  326. sql_str = helper.StringJoin(sql_str, " (", strings.Join(where, " and "), " ) ")
  327. }
  328. if len(where_or) > 0 {
  329. if len(where) > 0 {
  330. sql_str = helper.StringJoin(sql_str, " or ", strings.Join(where_or, " or "))
  331. } else {
  332. sql_str = helper.StringJoin(sql_str, strings.Join(where_or, " or "))
  333. }
  334. }
  335. if groupby != "" {
  336. sql_str = helper.StringJoin(sql_str, " group by ", groupby)
  337. }
  338. if having != "" {
  339. sql_str = helper.StringJoin(sql_str, " having ", having)
  340. }
  341. if orderby != "" {
  342. sql_str = helper.StringJoin(sql_str, " order by ", orderby)
  343. }
  344. if debug {
  345. log.Println("query sql:", sql_str, valueList)
  346. }
  347. condition_len := 0 //所有条件数
  348. for _, ch2 := range sql_str {
  349. if string(ch2) == "?" {
  350. condition_len++
  351. }
  352. }
  353. if condition_len != len(valueList) {
  354. return 0, nil, errors.New("参数错误,条件值错误")
  355. }
  356. var rows *sql.Rows
  357. var err error
  358. var queryNum int = 0
  359. sql_str = helper.StringJoin(sql_str, " limit 1")
  360. var db *sql.DB
  361. if SLAVER_DB != nil {
  362. db = SLAVER_DB
  363. } else {
  364. db = DB
  365. }
  366. for queryNum < 2 { //如发生错误,继续查询2次,防止数据库连接断开问题
  367. rows, err = db.Query(sql_str, valueList...)
  368. if err == nil {
  369. break
  370. } else {
  371. log.Println(err)
  372. time.Sleep(time.Millisecond * 500)
  373. }
  374. queryNum++
  375. }
  376. if err != nil {
  377. log.Println("DB error:", err)
  378. rows.Close()
  379. return count, info, err
  380. }
  381. columns, _ := rows.Columns()
  382. scanArgs := make([]interface{}, len(columns))
  383. values := make([]interface{}, len(columns))
  384. for i := range values {
  385. scanArgs[i] = &values[i]
  386. }
  387. var index string
  388. var rowerr error
  389. for rows.Next() {
  390. rowerr = rows.Scan(scanArgs...)
  391. if rowerr == nil {
  392. for i, col := range values {
  393. if col != nil {
  394. index = helper.StrFirstToUpper(columns[i])
  395. info[index] = helper.ToString(col)
  396. }
  397. }
  398. count++
  399. } else {
  400. log.Println("ERROR", rowerr)
  401. }
  402. }
  403. rows.Close()
  404. if rowerr != nil {
  405. log.Println("DB row error:", rowerr)
  406. return count, info, rowerr
  407. }
  408. return count, info, nil
  409. }
  410. /**
  411. * 查找多条记录
  412. * @param dbName 数据表名
  413. * @param title 查询字段名
  414. */
  415. 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) {
  416. var count int = 0
  417. list := make([]map[string]string, 0)
  418. if dbName == "" && table_name == "" {
  419. return count, list, errors.New("没有数据表")
  420. }
  421. table := ""
  422. if strings.Contains(table_name, "select ") || strings.HasPrefix(table, "(") {
  423. table = table_name
  424. } else {
  425. table = getTableName(dbName, table_name)
  426. }
  427. var sql_str, title string
  428. if titles != "" {
  429. title = titles
  430. } else {
  431. title = "*"
  432. }
  433. withSql := ""
  434. if len(with) > 0 {
  435. var builder strings.Builder
  436. builder.WriteString("WITH ")
  437. boo := false
  438. for k, v := range with {
  439. if len(v) < 2 {
  440. continue
  441. }
  442. if k != 0 {
  443. builder.WriteString(", ")
  444. }
  445. builder.WriteString(v[1])
  446. builder.WriteString(" as (")
  447. builder.WriteString(v[0])
  448. builder.WriteString(")")
  449. boo = true
  450. }
  451. if boo {
  452. builder.WriteString(" ")
  453. withSql = builder.String()
  454. }
  455. }
  456. if DB_PROVIDER == "TencentDB" {
  457. sql_str = helper.StringJoin("/*slave*/ ", withSql, " select ", title)
  458. } else {
  459. sql_str = helper.StringJoin(withSql, "select ", title)
  460. }
  461. if alias != "" {
  462. table = helper.StringJoin(table, " as ", alias)
  463. }
  464. sql_str = helper.StringJoin(sql_str, " from ", table)
  465. if len(join) > 0 {
  466. var builder strings.Builder
  467. for _, joinitem := range join {
  468. if len(joinitem) < 2 {
  469. continue
  470. }
  471. builder.WriteString(sql_str)
  472. builder.WriteString(" ")
  473. if len(joinitem) >= 3 {
  474. builder.WriteString(joinitem[2])
  475. } else {
  476. builder.WriteString("left")
  477. }
  478. builder.WriteString(" join ")
  479. if strings.Contains(joinitem[0], "select ") || strings.HasPrefix(joinitem[0], "(") || len(joinitem) > 4 {
  480. builder.WriteString(joinitem[0])
  481. } else {
  482. builder.WriteString(getTableName(dbName, joinitem[0]))
  483. }
  484. builder.WriteString(" on ")
  485. builder.WriteString(joinitem[1])
  486. }
  487. if builder.Len() > 0 {
  488. sql_str = builder.String()
  489. }
  490. }
  491. if len(where) > 0 || len(where_or) > 0 {
  492. sql_str = helper.StringJoin(sql_str, " where ")
  493. }
  494. if len(where) > 0 {
  495. sql_str = helper.StringJoin(sql_str, " (", strings.Join(where, " and "), " ) ")
  496. }
  497. if len(where_or) > 0 {
  498. if len(where) > 0 {
  499. sql_str = helper.StringJoin(sql_str, " or ", strings.Join(where_or, " or "))
  500. } else {
  501. sql_str = helper.StringJoin(sql_str, strings.Join(where_or, " or "))
  502. }
  503. }
  504. if groupby != "" {
  505. sql_str = helper.StringJoin(sql_str, " group by ", groupby)
  506. }
  507. if having != "" {
  508. sql_str = helper.StringJoin(sql_str, " HAVING ", having)
  509. }
  510. if orderby != "" {
  511. sql_str = helper.StringJoin(sql_str, " order by ", orderby)
  512. }
  513. if page > 0 || page_size > 0 {
  514. if page < 1 {
  515. page = 1
  516. }
  517. if page_size < 1 {
  518. page_size = 10
  519. }
  520. from := strconv.Itoa((page - 1) * page_size)
  521. offset := strconv.Itoa(page_size)
  522. if from != "" && offset != "" {
  523. sql_str = helper.StringJoin(sql_str, " limit ", from, " , ", offset)
  524. }
  525. }
  526. if debug {
  527. log.Println("query sql:", sql_str, valueList)
  528. }
  529. condition_len := 0 //所有条件数
  530. for _, ch2 := range sql_str {
  531. if string(ch2) == "?" {
  532. condition_len++
  533. }
  534. }
  535. if condition_len != len(valueList) {
  536. return 0, list, errors.New("参数错误,条件值错误")
  537. }
  538. var db *sql.DB
  539. if SLAVER_DB != nil {
  540. db = SLAVER_DB
  541. } else {
  542. db = DB
  543. }
  544. var rows *sql.Rows
  545. var err error
  546. var queryNum int = 0
  547. for queryNum < 2 { //如发生错误,继续查询2次,防止数据库连接断开问题
  548. rows, err = db.Query(sql_str, valueList...)
  549. if err == nil {
  550. break
  551. } else {
  552. log.Println(err)
  553. time.Sleep(time.Millisecond * 500)
  554. }
  555. queryNum++
  556. }
  557. if err != nil {
  558. rows.Close()
  559. return 0, list, err
  560. }
  561. columns, _ := rows.Columns()
  562. scanArgs := make([]interface{}, len(columns))
  563. values := make([]interface{}, len(columns))
  564. for i := range values {
  565. scanArgs[i] = &values[i]
  566. }
  567. var index string
  568. var rowerr error
  569. var info map[string]string
  570. for rows.Next() {
  571. rowerr = rows.Scan(scanArgs...)
  572. info = make(map[string]string)
  573. if rowerr == nil {
  574. for i, col := range values {
  575. if col != nil {
  576. index = helper.StrFirstToUpper(columns[i])
  577. info[index] = helper.ToString(col)
  578. }
  579. }
  580. count++
  581. } else {
  582. log.Println("ERROR", rowerr)
  583. }
  584. if len(info) > 0 {
  585. list = append(list, info)
  586. }
  587. }
  588. rows.Close()
  589. return count, list, nil
  590. }
  591. func GetInfo(dbName, table string, title string, where map[string]string) (map[string]string, error) {
  592. count, info, gzErr := GetData(dbName, table, title, where, nil)
  593. if gzErr != nil {
  594. return info, gzErr
  595. } else {
  596. if count < 1 {
  597. return info, errors.New("No data")
  598. }
  599. return info, nil
  600. }
  601. }
  602. /**
  603. * 查询列表
  604. * 2018/04/19
  605. */
  606. func GetList(dbName, table string, title string, where map[string]string, limit map[string]string) ([]map[string]string, error) {
  607. var list []map[string]string
  608. if dbName == "" && table == "" {
  609. return list, errors.New("没有数据表")
  610. }
  611. if strings.Contains(table, "select ") {
  612. dbName = table
  613. } else {
  614. dbName = getTableName(dbName, table)
  615. }
  616. var rows *sql.Rows
  617. var err error
  618. var queryNum int = 0
  619. var limitStr string = ""
  620. if len(limit) > 0 {
  621. var offset string = "0" //偏移量,个数
  622. var from string = "" //开始
  623. if _, ok := limit["order"]; ok {
  624. limitStr += " order by " + limit["order"]
  625. }
  626. if _, ok := limit["offset"]; ok {
  627. offset = limit["offset"]
  628. }
  629. if _, ok := limit["from"]; ok {
  630. from = limit["from"]
  631. }
  632. if offset != "0" && from != "" {
  633. limitStr += " limit " + from + "," + offset
  634. }
  635. }
  636. if len(where) > 0 {
  637. valueList := make([]interface{}, len(where))
  638. whereStr := make([]string, len(where))
  639. i := 0
  640. var keys []string
  641. for key, value := range where {
  642. key = strings.Trim(key, " ")
  643. value = strings.Trim(value, " ")
  644. if value == "" || key == "" {
  645. continue
  646. // return list, errors.New("Query condition is empty")
  647. }
  648. if strings.Contains(key, " ") {
  649. //key中包含空格,判断是否不等于条件
  650. keys = strings.Split(key, " ")
  651. if helper.IsInStringArray(judg(), strings.Trim(keys[1], " ")) {
  652. whereStr[i] = strings.Trim(keys[0], " ") + " " + strings.Trim(keys[1], " ") + " ?"
  653. }
  654. } else {
  655. whereStr[i] = key + " = ?"
  656. valueList[i] = value
  657. }
  658. i++
  659. }
  660. if len(whereStr) == 0 || len(valueList) == 0 {
  661. return list, errors.New("Query condition is empty")
  662. }
  663. for queryNum < 5 { //如发生错误,继续查询5次,防止数据库连接断开问题
  664. rows, err = DB.Query("select "+title+" from "+dbName+" where "+strings.Join(whereStr, " and ")+" "+limitStr, valueList...)
  665. if err == nil {
  666. break
  667. } else {
  668. time.Sleep(time.Millisecond * 500)
  669. }
  670. queryNum++
  671. }
  672. } else {
  673. for queryNum < 5 { //如发生错误,继续查询5次,防止数据库连接断开问题
  674. rows, err = DB.Query("select " + title + " from " + dbName + " " + limitStr)
  675. if err == nil {
  676. break
  677. } else {
  678. time.Sleep(time.Millisecond * 500)
  679. }
  680. queryNum++
  681. }
  682. }
  683. if err != nil {
  684. return list, err
  685. }
  686. defer rows.Close()
  687. columns, _ := rows.Columns()
  688. scanArgs := make([]interface{}, len(columns))
  689. values := make([]interface{}, len(columns))
  690. for i := range values {
  691. scanArgs[i] = &values[i]
  692. }
  693. var record map[string]string
  694. var index string
  695. for rows.Next() {
  696. //将行数据保存到record字典
  697. err = rows.Scan(scanArgs...)
  698. record = make(map[string]string)
  699. for i, col := range values {
  700. if col != nil {
  701. index = helper.StrFirstToUpper(columns[i])
  702. record[index] = helper.ToString(col)
  703. }
  704. }
  705. list = append(list, record)
  706. }
  707. return list, nil
  708. }
  709. /**
  710. * 查询总数
  711. * 2018/04/19
  712. */
  713. func GetTotal(dbName, table string, args ...string) (total int) {
  714. if dbName == "" && table == "" {
  715. return
  716. }
  717. if strings.Contains(table, "select ") {
  718. dbName = table
  719. } else {
  720. dbName = getTableName(dbName, table)
  721. }
  722. var title string = "*"
  723. if len(args) > 0 {
  724. title = args[0]
  725. }
  726. var rows *sql.Rows
  727. var err error
  728. var queryNum int = 0
  729. for queryNum < 5 { //如发生错误,继续查询5次,防止数据库连接断开问题
  730. rows, err = DB.Query("select count(" + title + ") as count from " + dbName + " limit 1")
  731. if err == nil {
  732. break
  733. } else {
  734. time.Sleep(time.Millisecond * 500)
  735. }
  736. queryNum++
  737. }
  738. if err != nil {
  739. log.Println("ERROR|get", dbName, "total error", err)
  740. return
  741. }
  742. defer rows.Close()
  743. var count int
  744. for rows.Next() {
  745. //将行数据保存到record字典
  746. err = rows.Scan(&count)
  747. if err != nil {
  748. log.Println("ERROR|get", dbName, "total error", err)
  749. } else {
  750. total = count
  751. }
  752. }
  753. return
  754. }
  755. /**
  756. * 查询总数
  757. * 2020/06/04
  758. */
  759. func GetCount(dbName, table string, where map[string]string, args ...string) (total int) {
  760. if dbName == "" && table == "" {
  761. return
  762. }
  763. if strings.Contains(table, "select ") {
  764. dbName = table
  765. } else {
  766. dbName = getTableName(dbName, table)
  767. }
  768. var title string = "*"
  769. if len(title) > 0 {
  770. title = args[0]
  771. }
  772. var rows *sql.Rows
  773. var err error
  774. var queryNum int = 0
  775. if len(where) > 0 {
  776. valueList := make([]interface{}, len(where))
  777. whereStr := make([]string, len(where))
  778. i := 0
  779. var keys []string
  780. for key, value := range where {
  781. key = strings.Trim(key, " ")
  782. value = strings.Trim(value, " ")
  783. if value == "" || key == "" {
  784. continue
  785. // return list, errors.New("Query condition is empty")
  786. }
  787. if strings.Contains(key, " ") {
  788. //key中包含空格,判断是否不等于条件
  789. keys = strings.Split(key, " ")
  790. if helper.IsInStringArray(judg(), strings.Trim(keys[1], " ")) {
  791. whereStr[i] = strings.Trim(keys[0], " ") + " " + strings.Trim(keys[1], " ") + " ?"
  792. }
  793. } else {
  794. whereStr[i] = key + " = ?"
  795. valueList[i] = value
  796. }
  797. i++
  798. }
  799. for queryNum < 5 { //如发生错误,继续查询5次,防止数据库连接断开问题
  800. rows, err = DB.Query("select count("+title+") as count from "+dbName+" where "+strings.Join(whereStr, " and ")+" limit 1", valueList...)
  801. if err == nil {
  802. break
  803. } else {
  804. time.Sleep(time.Millisecond * 500)
  805. }
  806. queryNum++
  807. }
  808. } else {
  809. for queryNum < 5 { //如发生错误,继续查询5次,防止数据库连接断开问题
  810. rows, err = DB.Query("select count(" + title + ") as count from " + dbName + " limit 1")
  811. if err == nil {
  812. break
  813. } else {
  814. time.Sleep(time.Millisecond * 500)
  815. }
  816. queryNum++
  817. }
  818. }
  819. if err != nil {
  820. log.Println("ERROR|get", dbName, "count error", err)
  821. return
  822. }
  823. defer rows.Close()
  824. var count int
  825. for rows.Next() {
  826. //将行数据保存到record字典
  827. err = rows.Scan(&count)
  828. if err != nil {
  829. log.Println("ERROR|get", dbName, "count error", err)
  830. } else {
  831. total = count
  832. }
  833. }
  834. return
  835. }
  836. func DoQuery(args ...interface{}) ([]map[string]string, error) {
  837. var list []map[string]string
  838. if len(args) < 1 {
  839. return list, errors.New("Query condition is empty")
  840. }
  841. queryStr := helper.ToString(args[0])
  842. if queryStr == "" {
  843. return list, errors.New("Query condition is empty")
  844. }
  845. var rows *sql.Rows
  846. var err error
  847. var queryNum int = 0
  848. for queryNum < 3 { //如发生错误,继续查询5次,防止数据库连接断开问题
  849. if len(args) > 1 {
  850. rows, err = DB.Query(queryStr, args[1:]...) //strings.Join(args[1:], ",")
  851. if err != nil {
  852. log.Println("ERROR|DoQuery error:", err)
  853. }
  854. } else {
  855. rows, err = DB.Query(queryStr)
  856. if err != nil {
  857. log.Println("ERROR|DoQuery error:", err)
  858. }
  859. }
  860. if err == nil {
  861. break
  862. } else {
  863. time.Sleep(time.Millisecond * 500)
  864. }
  865. queryNum++
  866. }
  867. if err != nil {
  868. return list, err
  869. }
  870. defer rows.Close()
  871. columns, _ := rows.Columns()
  872. scanArgs := make([]interface{}, len(columns))
  873. values := make([]interface{}, len(columns))
  874. for i := range values {
  875. scanArgs[i] = &values[i]
  876. }
  877. var record map[string]string
  878. var index string
  879. for rows.Next() {
  880. //将行数据保存到record字典
  881. err = rows.Scan(scanArgs...)
  882. record = make(map[string]string)
  883. for i, col := range values {
  884. if col != nil {
  885. index = helper.StrFirstToUpper(columns[i])
  886. record[index] = helper.ToString(col)
  887. }
  888. }
  889. list = append(list, record)
  890. }
  891. return list, nil
  892. }