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

629 lines
13 KiB

3 years ago
  1. package dbquery
  2. import (
  3. "database/sql"
  4. "log"
  5. "errors"
  6. "strings"
  7. "time"
  8. "git.tetele.net/tgo/helper"
  9. _ "github.com/go-sql-driver/mysql"
  10. )
  11. /**
  12. * 创建数据
  13. */
  14. func Insert(dbName, table string, data map[string]string) (int64, error) {
  15. var insertId int64
  16. var err error
  17. if dbName == "" && table == "" {
  18. return insertId, errors.New("没有数据表")
  19. }
  20. dbName = getTableName(dbName, table)
  21. if len(data) < 1 {
  22. return insertId, errors.New("没有要写入的数据")
  23. }
  24. keyList := make([]string, len(data))
  25. keyStr := make([]string, len(data))
  26. valueList := make([]interface{}, len(data))
  27. var i int = 0
  28. for key, value := range data {
  29. keyList[i] = key
  30. keyStr[i] = "?"
  31. valueList[i] = value
  32. i++
  33. }
  34. result, err := DB.Exec("insert into "+dbName+" ("+strings.Join(keyList, ",")+") value("+strings.Join(keyStr, ",")+")", valueList...)
  35. if err != nil {
  36. log.Println("ERROR|插入", dbName, "数据失败,", err)
  37. return insertId, err
  38. } else {
  39. insertId, _ = result.LastInsertId()
  40. time.Sleep(time.Second * 2)
  41. return insertId, nil
  42. }
  43. }
  44. /**
  45. * 修改数据
  46. */
  47. func Update(dbName, table string, data map[string]string, where map[string]string) (int64, error) {
  48. var rowsAffected int64
  49. var err error
  50. if dbName == "" && table == "" {
  51. return rowsAffected, errors.New("没有数据表")
  52. }
  53. dbName = getTableName(dbName, table)
  54. if len(data) < 1 {
  55. return rowsAffected, errors.New("同有更新的数据")
  56. }
  57. if len(where) < 1 {
  58. return rowsAffected, errors.New("没有更新条件")
  59. }
  60. keyList := make([]string, len(data))
  61. valueList := make([]interface{}, len(data), len(data)+len(where))
  62. whereStr := make([]string, len(where))
  63. var i int = 0
  64. empty := false
  65. for key, value := range data {
  66. keyList[i] = key + "=?"
  67. valueList[i] = value
  68. i++
  69. }
  70. i = 0
  71. for key, value := range where {
  72. if value == "" {
  73. empty = true
  74. break
  75. }
  76. whereStr[i] = key + "=?"
  77. valueList = append(valueList, value)
  78. i++
  79. }
  80. if empty {
  81. log.Println("ERROR|修改数据表", dbName, "时条件中有空数据,条件:", where, "数据:", data)
  82. return rowsAffected, errors.New("条件中有空数据")
  83. }
  84. result, err := DB.Exec("update "+dbName+" set "+strings.Join(keyList, " , ")+" where "+strings.Join(whereStr, " and "), valueList...)
  85. if err != nil {
  86. log.Println("ERROR|修改", dbName, "数据失败,", err)
  87. return rowsAffected, err
  88. } else {
  89. rowsAffected, _ = result.RowsAffected()
  90. return rowsAffected, nil
  91. }
  92. }
  93. /**
  94. * 删除数据
  95. * @param count 删除数量
  96. */
  97. func Delete(dbName, table string, data map[string]string, del_count ...string) (int64, error) {
  98. var count int64
  99. var err error
  100. if dbName == "" && table == "" {
  101. return count, errors.New("没有数据表")
  102. }
  103. dbName = getTableName(dbName, table)
  104. if len(data) < 1 {
  105. return count, errors.New("没有要删除的数据")
  106. }
  107. keyList := make([]string, len(data))
  108. valueList := make([]interface{}, len(data))
  109. var i int = 0
  110. empty := false
  111. for key, value := range data {
  112. if value == "" {
  113. empty = true
  114. break
  115. }
  116. keyList[i] = key + "=?"
  117. valueList[i] = value
  118. i++
  119. }
  120. if empty {
  121. log.Println("ERROR|删除数据表", dbName, "时条件中有空数据,条件:", data)
  122. return count, errors.New("条件中有空数据")
  123. }
  124. var limitStr string = ""
  125. if len(del_count) > 0 {
  126. limitStr = " limit " + del_count[0]
  127. }
  128. result, err := DB.Exec("delete from "+dbName+" where "+strings.Join(keyList, " and ")+limitStr, valueList...)
  129. if err != nil {
  130. log.Println("ERROR|删除", dbName, "数据失败,", err)
  131. return count, err
  132. } else {
  133. count, _ = result.RowsAffected()
  134. return count, nil
  135. }
  136. }
  137. /**
  138. * 查找一条记录
  139. * @param dbName 数据表名
  140. * @param title 查询字段名
  141. */
  142. func GetData(dbName, table string, title string, where map[string]string, limit map[string]string) (int, map[string]string, error) {
  143. var count int = 0
  144. info := make(map[string]string)
  145. if dbName == "" && table == "" {
  146. return count, info, errors.New("没有数据表")
  147. }
  148. dbName = getTableName(dbName, table)
  149. if len(title) < 1 {
  150. return count, info, errors.New("没有指定查询内容")
  151. }
  152. var limitStr string = ""
  153. if limit != nil && len(limit) > 0 {
  154. var from string = "0" //开始
  155. if _, ok := limit["order"]; ok {
  156. limitStr += " order by " + limit["order"]
  157. }
  158. if _, ok := limit["from"]; ok {
  159. from = limit["from"]
  160. }
  161. limitStr += " limit " + from + ",1"
  162. } else {
  163. limitStr = " limit 1"
  164. }
  165. if len(where) < 1 {
  166. return count, info, errors.New("Query condition is empty")
  167. }
  168. keyList := make([]string, len(where))
  169. valueList := make([]interface{}, len(where))
  170. var i int = 0
  171. empty := false
  172. for key, value := range where {
  173. if value == "" {
  174. empty = true
  175. break
  176. }
  177. keyList[i] = key + " = ? "
  178. valueList[i] = value
  179. i++
  180. }
  181. if empty {
  182. return count, info, errors.New("Query condition is empty")
  183. }
  184. var rows *sql.Rows
  185. var err error
  186. var queryNum int = 0
  187. for queryNum < 3 { //如发生错误,继续查询3次,防止数据库连接断开问题
  188. rows, err = DB.Query("SELECT "+title+" FROM "+dbName+" where "+strings.Join(keyList, " and ")+" "+limitStr, valueList...)
  189. if err == nil {
  190. break
  191. } else {
  192. log.Println("ERROR", "Query from", dbName, "failed,", err, "| SELECT "+title+" FROM "+dbName+" where "+strings.Join(keyList, " and ")+" "+limitStr)
  193. time.Sleep(time.Millisecond * 500)
  194. }
  195. queryNum++
  196. }
  197. defer rows.Close()
  198. if err != nil {
  199. return count, info, err
  200. }
  201. columns, _ := rows.Columns()
  202. scanArgs := make([]interface{}, len(columns))
  203. values := make([]interface{}, len(columns))
  204. for i := range values {
  205. scanArgs[i] = &values[i]
  206. }
  207. var index string
  208. var rowerr error
  209. for rows.Next() {
  210. rowerr = rows.Scan(scanArgs...)
  211. if rowerr == nil {
  212. for i, col := range values {
  213. if col != nil {
  214. index = helper.StrFirstToUpper(columns[i])
  215. info[index] = helper.ToString(col)
  216. }
  217. }
  218. count++
  219. } else {
  220. log.Println("ERROR", "rows scan error", rowerr, dbName, keyList, valueList)
  221. }
  222. }
  223. if rowerr != nil {
  224. return count, info, rowerr
  225. }
  226. return count, info, nil
  227. }
  228. func GetInfo(dbName, table string, title string, where map[string]string) (map[string]string, error) {
  229. count, info, gzErr := GetData(dbName, table, title, where, nil)
  230. if gzErr != nil {
  231. return info, gzErr
  232. } else {
  233. if count < 1 {
  234. return info, errors.New("No data")
  235. }
  236. return info, nil
  237. }
  238. }
  239. /**
  240. * 查询列表
  241. * 2018/04/19
  242. */
  243. func GetList(dbName, table string, title string, where map[string]string, limit map[string]string) ([]map[string]string, error) {
  244. var list []map[string]string
  245. if dbName == "" && table == "" {
  246. return list, errors.New("没有数据表")
  247. }
  248. dbName = getTableName(dbName, table)
  249. var rows *sql.Rows
  250. var err error
  251. var queryNum int = 0
  252. var limitStr string = ""
  253. if len(limit) > 0 {
  254. var offset string = "0" //偏移量,个数
  255. var from string = "" //开始
  256. if _, ok := limit["order"]; ok {
  257. limitStr += " order by " + limit["order"]
  258. }
  259. if _, ok := limit["offset"]; ok {
  260. offset = limit["offset"]
  261. }
  262. if _, ok := limit["from"]; ok {
  263. from = limit["from"]
  264. }
  265. if offset != "0" && from != "" {
  266. limitStr += " limit " + from + "," + offset
  267. }
  268. }
  269. if len(where) > 0 {
  270. valueList := make([]interface{}, len(where))
  271. whereStr := make([]string, len(where))
  272. i := 0
  273. var keys []string
  274. for key, value := range where {
  275. key = strings.Trim(key, " ")
  276. value = strings.Trim(value, " ")
  277. if value == "" || key == "" {
  278. continue
  279. // return list, errors.New("Query condition is empty")
  280. }
  281. if strings.Contains(key, " ") {
  282. //key中包含空格,判断是否不等于条件
  283. keys = strings.Split(key, " ")
  284. if helper.IsInStringArray(judg(), strings.Trim(keys[1], " ")) {
  285. whereStr[i] = strings.Trim(keys[0], " ") + " " + strings.Trim(keys[1], " ") + " ?"
  286. }
  287. } else {
  288. whereStr[i] = key + " = ?"
  289. valueList[i] = value
  290. }
  291. i++
  292. }
  293. if len(whereStr) == 0 || len(valueList) == 0 {
  294. return list, errors.New("Query condition is empty")
  295. }
  296. for queryNum < 5 { //如发生错误,继续查询5次,防止数据库连接断开问题
  297. rows, err = DB.Query("select "+title+" from "+dbName+" where "+strings.Join(whereStr, " and ")+" "+limitStr, valueList...)
  298. if err == nil {
  299. break
  300. } else {
  301. time.Sleep(time.Millisecond * 500)
  302. }
  303. queryNum++
  304. }
  305. } else {
  306. for queryNum < 5 { //如发生错误,继续查询5次,防止数据库连接断开问题
  307. rows, err = DB.Query("select " + title + " from " + dbName + " " + limitStr)
  308. if err == nil {
  309. break
  310. } else {
  311. time.Sleep(time.Millisecond * 500)
  312. }
  313. queryNum++
  314. }
  315. }
  316. if err != nil {
  317. return list, err
  318. }
  319. defer rows.Close()
  320. columns, _ := rows.Columns()
  321. scanArgs := make([]interface{}, len(columns))
  322. values := make([]interface{}, len(columns))
  323. for i := range values {
  324. scanArgs[i] = &values[i]
  325. }
  326. var record map[string]string
  327. var index string
  328. for rows.Next() {
  329. //将行数据保存到record字典
  330. err = rows.Scan(scanArgs...)
  331. record = make(map[string]string)
  332. for i, col := range values {
  333. if col != nil {
  334. index = helper.StrFirstToUpper(columns[i])
  335. record[index] = helper.ToString(col)
  336. }
  337. }
  338. list = append(list, record)
  339. }
  340. return list, nil
  341. }
  342. /**
  343. * 查询总数
  344. * 2018/04/19
  345. */
  346. func GetTotal(dbName, table string, args ...string) (total int) {
  347. if dbName == "" && table == "" {
  348. return
  349. }
  350. dbName = getTableName(dbName, table)
  351. var title string = "*"
  352. if len(args) > 0 {
  353. title = args[0]
  354. }
  355. var rows *sql.Rows
  356. var err error
  357. var queryNum int = 0
  358. for queryNum < 5 { //如发生错误,继续查询5次,防止数据库连接断开问题
  359. rows, err = DB.Query("select count(" + title + ") as count from " + dbName + " limit 1")
  360. if err == nil {
  361. break
  362. } else {
  363. time.Sleep(time.Millisecond * 500)
  364. }
  365. queryNum++
  366. }
  367. if err != nil {
  368. log.Println("ERROR|get", dbName, "total error", err)
  369. return
  370. }
  371. defer rows.Close()
  372. var count int
  373. for rows.Next() {
  374. //将行数据保存到record字典
  375. err = rows.Scan(&count)
  376. if err != nil {
  377. log.Println("ERROR|get", dbName, "total error", err)
  378. } else {
  379. total = count
  380. }
  381. }
  382. return
  383. }
  384. /**
  385. * 查询总数
  386. * 2020/06/04
  387. */
  388. func GetCount(dbName, table string, where map[string]string, args ...string) (total int) {
  389. if dbName == "" && table == "" {
  390. return
  391. }
  392. dbName = getTableName(dbName, table)
  393. var title string = "*"
  394. if len(title) > 0 {
  395. title = args[0]
  396. }
  397. var rows *sql.Rows
  398. var err error
  399. var queryNum int = 0
  400. if len(where) > 0 {
  401. valueList := make([]interface{}, len(where))
  402. whereStr := make([]string, len(where))
  403. i := 0
  404. var keys []string
  405. for key, value := range where {
  406. key = strings.Trim(key, " ")
  407. value = strings.Trim(value, " ")
  408. if value == "" || key == "" {
  409. continue
  410. // return list, errors.New("Query condition is empty")
  411. }
  412. if strings.Contains(key, " ") {
  413. //key中包含空格,判断是否不等于条件
  414. keys = strings.Split(key, " ")
  415. if helper.IsInStringArray(judg(), strings.Trim(keys[1], " ")) {
  416. whereStr[i] = strings.Trim(keys[0], " ") + " " + strings.Trim(keys[1], " ") + " ?"
  417. }
  418. } else {
  419. whereStr[i] = key + " = ?"
  420. valueList[i] = value
  421. }
  422. i++
  423. }
  424. for queryNum < 5 { //如发生错误,继续查询5次,防止数据库连接断开问题
  425. rows, err = DB.Query("select count("+title+") as count from "+dbName+" where "+strings.Join(whereStr, " and ")+" limit 1", valueList...)
  426. if err == nil {
  427. break
  428. } else {
  429. time.Sleep(time.Millisecond * 500)
  430. }
  431. queryNum++
  432. }
  433. } else {
  434. for queryNum < 5 { //如发生错误,继续查询5次,防止数据库连接断开问题
  435. rows, err = DB.Query("select count(" + title + ") as count from " + dbName + " limit 1")
  436. if err == nil {
  437. break
  438. } else {
  439. time.Sleep(time.Millisecond * 500)
  440. }
  441. queryNum++
  442. }
  443. }
  444. if err != nil {
  445. log.Println("ERROR|get", dbName, "count error", err)
  446. return
  447. }
  448. defer rows.Close()
  449. var count int
  450. for rows.Next() {
  451. //将行数据保存到record字典
  452. err = rows.Scan(&count)
  453. if err != nil {
  454. log.Println("ERROR|get", dbName, "count error", err)
  455. } else {
  456. total = count
  457. }
  458. }
  459. return
  460. }
  461. func DoQuery(args ...interface{}) ([]map[string]string, error) {
  462. var list []map[string]string
  463. if len(args) < 1 {
  464. return list, errors.New("Query condition is empty")
  465. }
  466. queryStr := helper.ToString(args[0])
  467. if queryStr == "" {
  468. return list, errors.New("Query condition is empty")
  469. }
  470. var rows *sql.Rows
  471. var err error
  472. var queryNum int = 0
  473. for queryNum < 3 { //如发生错误,继续查询5次,防止数据库连接断开问题
  474. if len(args) > 1 {
  475. rows, err = DB.Query(queryStr, args[1:]...) //strings.Join(args[1:], ",")
  476. if err != nil {
  477. log.Println("ERROR|DoQuery error:", err)
  478. }
  479. } else {
  480. rows, err = DB.Query(queryStr)
  481. if err != nil {
  482. log.Println("ERROR|DoQuery error:", err)
  483. }
  484. }
  485. if err == nil {
  486. break
  487. } else {
  488. time.Sleep(time.Millisecond * 500)
  489. }
  490. queryNum++
  491. }
  492. if err != nil {
  493. return list, err
  494. }
  495. defer rows.Close()
  496. columns, _ := rows.Columns()
  497. scanArgs := make([]interface{}, len(columns))
  498. values := make([]interface{}, len(columns))
  499. for i := range values {
  500. scanArgs[i] = &values[i]
  501. }
  502. var record map[string]string
  503. var index string
  504. for rows.Next() {
  505. //将行数据保存到record字典
  506. err = rows.Scan(scanArgs...)
  507. record = make(map[string]string)
  508. for i, col := range values {
  509. if col != nil {
  510. index = helper.StrFirstToUpper(columns[i])
  511. record[index] = helper.ToString(col)
  512. }
  513. }
  514. list = append(list, record)
  515. }
  516. return list, nil
  517. }