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

971 lines
21 KiB

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