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

458 lines
10 KiB

3 years ago
  1. package dbquery
  2. import (
  3. "database/sql"
  4. "errors"
  5. "log"
  6. "strings"
  7. "git.tetele.net/tgo/helper"
  8. )
  9. /**
  10. * 准备查询
  11. * return Stmt error
  12. */
  13. func StmtForRead(dbName, table string, title string, where []string, limit map[string]string) (*sql.Stmt, error) {
  14. if dbName == "" && table == "" {
  15. return nil, errors.New("参数错误,没有数据表")
  16. }
  17. dbName = getTableName(dbName, table)
  18. if len(title) < 1 {
  19. return nil, errors.New("没有要查询内容")
  20. }
  21. var limitStr string = ""
  22. if limit != nil && len(limit) > 0 {
  23. var from, offset string = "", "" //开始
  24. if _, ok := limit["order"]; ok {
  25. limitStr += " order by " + limit["order"]
  26. }
  27. if _, ok := limit["from"]; ok {
  28. from = limit["from"]
  29. }
  30. if _, ok := limit["offset"]; ok {
  31. offset = limit["offset"]
  32. }
  33. if from != "" && offset != "" {
  34. limitStr += " limit " + from + "," + offset
  35. }
  36. }
  37. var stmt *sql.Stmt
  38. var err error
  39. if len(where) > 0 {
  40. // log.Println("SELECT " + title + " FROM " + dbName + " where " + strings.Join(where, " and ") + limitStr)
  41. stmt, err = DB.Prepare("SELECT " + title + " FROM " + dbName + " where " + strings.Join(where, " and ") + limitStr)
  42. } else {
  43. // log.Println("SELECT " + title + " FROM " + dbName + limitStr)
  44. stmt, err = DB.Prepare("SELECT " + title + " FROM " + dbName + limitStr)
  45. }
  46. return stmt, err
  47. }
  48. func CloseStmt(stmt *sql.Stmt) error {
  49. return stmt.Close()
  50. }
  51. /**
  52. * 执行查询列表
  53. * return list error
  54. */
  55. func StmtForQueryList(stmt *sql.Stmt, valuelist []interface{}) ([]map[string]string, error) {
  56. if stmt == nil {
  57. return nil, errors.New("缺少必要参数")
  58. }
  59. // log.Println(valuelist...)
  60. rows, err := stmt.Query(valuelist...)
  61. defer stmt.Close()
  62. if err != nil {
  63. if stmt != nil {
  64. stmt.Close()
  65. }
  66. return nil, err
  67. }
  68. columns, _ := rows.Columns()
  69. scanArgs := make([]interface{}, len(columns))
  70. values := make([]interface{}, len(columns))
  71. for i := range values {
  72. scanArgs[i] = &values[i]
  73. }
  74. var list []map[string]string
  75. var index string
  76. var rowerr error
  77. info := make(map[string]string)
  78. for rows.Next() {
  79. rowerr = rows.Scan(scanArgs...)
  80. info = make(map[string]string)
  81. if rowerr == nil {
  82. for i, col := range values {
  83. if col != nil {
  84. index = helper.StrFirstToUpper(columns[i])
  85. info[index] = helper.ToString(col)
  86. }
  87. }
  88. } else {
  89. log.Println("rows scan error", rowerr)
  90. }
  91. if len(info) > 0 {
  92. list = append(list, info)
  93. }
  94. }
  95. return list, nil
  96. }
  97. /**
  98. * 执行查询一条数据
  99. * return row error
  100. */
  101. func StmtForQueryRow(stmt *sql.Stmt, valuelist []interface{}) (map[string]string, error) {
  102. if stmt == nil || len(valuelist) < 1 {
  103. return nil, errors.New("缺少必要参数")
  104. }
  105. rows, err := stmt.Query(valuelist...)
  106. defer stmt.Close()
  107. if err != nil {
  108. if stmt != nil {
  109. stmt.Close()
  110. }
  111. return nil, err
  112. }
  113. columns, _ := rows.Columns()
  114. scanArgs := make([]interface{}, len(columns))
  115. values := make([]interface{}, len(columns))
  116. for i := range values {
  117. scanArgs[i] = &values[i]
  118. }
  119. var index string
  120. var rowerr error
  121. info := make(map[string]string)
  122. for rows.Next() {
  123. rowerr = rows.Scan(scanArgs...)
  124. if rowerr == nil {
  125. for i, col := range values {
  126. if col != nil {
  127. index = helper.StrFirstToUpper(columns[i])
  128. info[index] = helper.ToString(col)
  129. }
  130. }
  131. } else {
  132. log.Println("rows scan error", rowerr)
  133. }
  134. }
  135. if rowerr != nil {
  136. return info, errors.New("数据出错")
  137. }
  138. return info, nil
  139. }
  140. /**
  141. * 准备更新
  142. * return Stmt error
  143. */
  144. func StmtForUpdate(dbName, table string, data []string, where []string) (*sql.Stmt, error) {
  145. if dbName == "" && table == "" {
  146. return nil, errors.New("参数错误,没有数据表")
  147. }
  148. dbName = getTableName(dbName, table)
  149. if len(where) < 1 {
  150. return nil, errors.New("参数错误,没有更新条件")
  151. }
  152. var stmt *sql.Stmt
  153. var err error
  154. stmt, err = DB.Prepare("update " + dbName + " set " + strings.Join(data, " , ") + " where " + strings.Join(where, " and "))
  155. return stmt, err
  156. }
  157. /**
  158. * 执行更新
  159. * return is_updated error
  160. */
  161. func StmtForUpdateExec(stmt *sql.Stmt, valuelist []interface{}) (int64, error) {
  162. res, err := stmt.Exec(valuelist...)
  163. if err != nil {
  164. return 0, errors.New("更新失败:" + err.Error())
  165. }
  166. return res.RowsAffected()
  167. }
  168. /**
  169. * 准备写入
  170. * return Stmt error
  171. */
  172. func StmtForInsert(dbName, table string, data []string) (*sql.Stmt, error) {
  173. if dbName == "" && table == "" {
  174. return nil, errors.New("参数错误,没有数据表")
  175. }
  176. dbName = getTableName(dbName, table)
  177. if len(data) < 1 {
  178. return nil, errors.New("参数错误,没有要写入的数据")
  179. }
  180. var stmt *sql.Stmt
  181. var err error
  182. stmt, err = DB.Prepare("insert into " + dbName + " set " + strings.Join(data, " , "))
  183. return stmt, err
  184. }
  185. /**
  186. * 执行写入
  187. * @return lastId error
  188. */
  189. func StmtForInsertExec(stmt *sql.Stmt, valuelist []interface{}) (int64, error) {
  190. res, err := stmt.Exec(valuelist...)
  191. if err != nil {
  192. return 0, errors.New("创建失败:" + err.Error())
  193. }
  194. return res.LastInsertId()
  195. }
  196. /**
  197. * 使用db prepare方式查询列表
  198. * @param dbName
  199. * @param title 查询的字段名
  200. * @param where 查询条件
  201. * @param valuelist 查询的条件值
  202. * @param limit 查询排序
  203. * @param page 查询范围可传两个值 pageNum,pageSize
  204. * GZ
  205. * 2020/05/19
  206. */
  207. func GetListByStmt(dbName string, table string, title string, where []string, valuelist []interface{}, limit map[string]string, page ...int) ([]map[string]string, error) {
  208. if len(page) > 0 {
  209. pageNum, pageSize := page[0], 10
  210. if len(page) > 1 {
  211. pageSize = page[1]
  212. }
  213. limit["from"], limit["offset"] = helper.GetPage(pageNum, pageSize)
  214. }
  215. stmt, err := StmtForRead(dbName, table, title, where, limit)
  216. if err != nil {
  217. return nil, err
  218. }
  219. defer stmt.Close()
  220. return StmtForQueryList(stmt, valuelist)
  221. }
  222. /**
  223. * 使用db prepare方式查询单条数据
  224. * @param dbName
  225. * @param title 查询的字段名
  226. * @param where 查询条件
  227. * @param valuelist 查询的条件值
  228. * @param limit 查询排序
  229. * GZ
  230. * 2020/05/19
  231. */
  232. func GetDataByStmt(dbName string, table string, title string, where []string, valuelist []interface{}, limit map[string]string) (map[string]string, error) {
  233. stmt, err := StmtForRead(dbName, table, title, where, limit)
  234. if err != nil {
  235. return nil, err
  236. }
  237. defer stmt.Close()
  238. return StmtForQueryRow(stmt, valuelist)
  239. }
  240. /**
  241. * 使用db prepare修改数据
  242. * @param dbName
  243. * @param title 查询的字段名
  244. * @param where 查询条件
  245. * @param valuelist 查询的条件值
  246. * @param limit 查询排序
  247. * GZ
  248. * 2020/05/19
  249. */
  250. func UpdateByStmt(dbName string, table string, data []string, where []string, valuelist []interface{}) (int64, error) {
  251. stmt, err := StmtForUpdate(dbName, table, data, where)
  252. if err != nil {
  253. return 0, err
  254. }
  255. defer stmt.Close()
  256. return StmtForUpdateExec(stmt, valuelist)
  257. }
  258. /**
  259. * 使用db prepare写入数据
  260. * @param dbName
  261. * @param table 表名
  262. * @param data 写入的字段
  263. * @param valuelist 写入的值
  264. * GZ
  265. * 2020/08/06
  266. */
  267. func InsertByStmt(dbName string, table string, data []string, valuelist []interface{}) (int64, error) {
  268. stmt, err := StmtForInsert(dbName, table, data)
  269. if err != nil {
  270. return 0, err
  271. }
  272. defer stmt.Close()
  273. return StmtForInsertExec(stmt, valuelist)
  274. }
  275. /**
  276. * 自定义查询
  277. * return Stmt error
  278. */
  279. func StmtForQuery(querysql string) (*sql.Stmt, error) {
  280. if querysql == "" {
  281. return nil, errors.New("参数错误,没有数据表")
  282. }
  283. var stmt *sql.Stmt
  284. var err error
  285. stmt, err = DB.Prepare(querysql)
  286. return stmt, err
  287. }
  288. /**
  289. * 执行自定义查询
  290. * @return lastId error
  291. */
  292. func QueryByStmt(sql string, valuelist []interface{}) ([]map[string]string, error) {
  293. stmt, err := StmtForQuery(sql)
  294. if err != nil {
  295. return nil, err
  296. }
  297. defer stmt.Close()
  298. return StmtForQueryList(stmt, valuelist)
  299. }
  300. /**
  301. * 联表查询
  302. * @param dbName
  303. * @param tableA 表一
  304. * @param tableA_alias 表一别名
  305. * @param tableB 表二
  306. * @param tableB_alias 表二别名
  307. * @param join 联表方式
  308. * @param join_on 联表字段
  309. * @param title 查询的字段名
  310. * @param where 查询条件
  311. * @param valuelist 查询的条件值
  312. * @param limit 查询排序
  313. * @param page 查询范围可传两个值 pageNum,pageSize
  314. * GZ
  315. * 2020/11/23
  316. */
  317. func GetJoinListByStmt(dbName string, tableA, tableA_alias string, tableB, tableB_alias string, join_type, join_on string, title string, where []string, valuelist []interface{}, limit map[string]string, page ...int) ([]map[string]string, error) {
  318. if len(page) > 0 {
  319. pageNum, pageSize := page[0], 10
  320. if len(page) > 1 {
  321. pageSize = page[1]
  322. }
  323. limit["from"], limit["offset"] = helper.GetPage(pageNum, pageSize)
  324. }
  325. if tableA_alias != "" {
  326. tableA = helper.StringJoin(dbName, ".", tableA, " as ", tableA_alias)
  327. }
  328. if tableB_alias != "" {
  329. tableB = helper.StringJoin(dbName, ".", tableB, " as ", tableB_alias)
  330. }
  331. table := helper.StringJoin(tableA, " ", join_type, " join ", tableB, " on ", join_on)
  332. stmt, err := StmtForRead(dbName, table, title, where, limit)
  333. if err != nil {
  334. return nil, err
  335. }
  336. defer stmt.Close()
  337. return StmtForQueryList(stmt, valuelist)
  338. }
  339. /**
  340. * 左联表查询
  341. * @param dbName
  342. * @param tableA 表一
  343. * @param tableB 表二
  344. * @param join_on 联表字段
  345. * @param title 查询的字段名
  346. * @param where 查询条件
  347. * @param valuelist 查询的条件值
  348. * @param limit 查询排序
  349. * @param page 查询范围可传两个值 pageNum,pageSize
  350. * GZ
  351. * 2021/1/27
  352. */
  353. func LeftJoinListByStmt(dbName string, tableA, tableB string, join_on string, title string, where []string, valuelist []interface{}, limit map[string]string, page ...int) ([]map[string]string, error) {
  354. if len(page) > 0 {
  355. pageNum, pageSize := page[0], 10
  356. if len(page) > 1 {
  357. pageSize = page[1]
  358. }
  359. limit["from"], limit["offset"] = helper.GetPage(pageNum, pageSize)
  360. }
  361. tableA = getTableName(dbName, tableA)
  362. tableB = getTableName(dbName, tableB)
  363. table := helper.StringJoin(tableA, " left join ", tableB, " on ", join_on)
  364. stmt, err := StmtForRead(dbName, table, title, where, limit)
  365. if err != nil {
  366. return nil, err
  367. }
  368. defer stmt.Close()
  369. return StmtForQueryList(stmt, valuelist)
  370. }