• go操作数据库(插入、更新、删除、查找、事务)


    1. package main
    2. import (
    3. "database/sql"
    4. "fmt"
    5. _ "github.com/go-sql-driver/mysql"
    6. "log"
    7. "time"
    8. )
    9. func init() {
    10. //sql.Register("mysql", &mysql.MySQLDriver{})
    11. }
    12. func main() {
    13. db, err := sql.Open("mysql", "root:root@tcp(localhost:3306)/hello?charset=utf8&parseTime=True")
    14. if err != nil {
    15. log.Fatal(err)
    16. return
    17. }
    18. defer db.Close()
    19. //InsterLikeInfo(db)
    20. //UpdateLikeInfo(db)
    21. FindLikeInfo(db, 1)
    22. DeleteLikeInfo(db, 9)
    23. InsertANDUpdateLikeInfo(db)
    24. }
    25. type LikeInfo struct {
    26. ID int `gorm:"primary_key"`
    27. Ip string `gorm:"type:varchar(20);not null;index:ip_idx"`
    28. Ua string `gorm:"type:varchar(256);not null;"`
    29. Title string `gorm:"Title"`
    30. Hash int `gorm:"Hash" column:"Hash"`
    31. CreatedAt time.Time `gorm:"CreatedAt" column:"CreatedAt"`
    32. }
    33. //插入
    34. func InsterLikeInfo(db *sql.DB) {
    35. var like = &LikeInfo{
    36. Ip: "127.0.0.1",
    37. Ua: "ua",
    38. Title: "like me",
    39. Hash: 120,
    40. CreatedAt: time.Now(),
    41. }
    42. insertSQL := ` INSERT INTO LikeInfo
    43. (Ip, Ua, Title, Hash,CreatedAt)
    44. VALUES
    45. (?, ?, ?, ?, ?);`
    46. stmt, err := db.Prepare(insertSQL)
    47. if err != nil {
    48. return
    49. }
    50. defer stmt.Close()
    51. result, err := stmt.Exec(like.Ip, like.Ua, like.Title, like.Hash, like.CreatedAt)
    52. if err != nil {
    53. return
    54. }
    55. id, err := result.LastInsertId()
    56. if err != nil {
    57. return
    58. }
    59. fmt.Println("返回id:", id)
    60. }
    61. //更新
    62. func UpdateLikeInfo(db *sql.DB) {
    63. var like = &LikeInfo{
    64. ID: 1,
    65. Ip: "127.0.0.1",
    66. Ua: "newUa",
    67. Title: "like you",
    68. Hash: 111,
    69. CreatedAt: time.Now(),
    70. }
    71. updateSQL := `UPDATE LikeInfo
    72. SET Ip = ?, Ua=?, Title = ?, Hash = ?, CreatedAt = ?
    73. WHERE ID = ?;`
    74. _, err := db.Exec(updateSQL, like.Ip, like.Ua, like.Title, like.Hash, like.CreatedAt, like.ID)
    75. if err != nil {
    76. return
    77. }
    78. //fmt.Println("更新结果:", result)
    79. }
    80. //查找
    81. func FindLikeInfo(db *sql.DB, id int) {
    82. var like LikeInfo
    83. querySQL := `SELECT ID,Ua,IP,Hash,Title,CreatedAt FROM LikeInfo where ID = ?;`
    84. err := db.QueryRow(querySQL, id).Scan(&like.ID, &like.Ua, &like.Ip, &like.Hash, &like.Title, &like.CreatedAt)
    85. if err != nil {
    86. return
    87. }
    88. fmt.Printf("结果:%#+v\n", like)
    89. }
    90. //删除
    91. func DeleteLikeInfo(db *sql.DB, id int) {
    92. deleteSQl := `delete from LikeInfo where ID= ?;`
    93. _, err := db.Exec(deleteSQl, id)
    94. if err != nil {
    95. fmt.Println(err)
    96. return
    97. }
    98. }
    99. //事务
    100. func InsertANDUpdateLikeInfo(db *sql.DB) {
    101. var like = &LikeInfo{
    102. ID: 1,
    103. Ip: "127.0.0.1",
    104. Ua: "newUa",
    105. Title: "like you",
    106. Hash: 111,
    107. CreatedAt: time.Now(),
    108. }
    109. tx, err := db.Begin()
    110. if err != nil {
    111. if tx == nil {
    112. tx.Rollback()
    113. fmt.Printf("开启事务失败,错误:%v\n", err)
    114. return
    115. }
    116. }
    117. insertSQL := ` INSERT INTO LikeInfo
    118. (Ip, Ua, Title, Hash,CreatedAt)
    119. VALUES
    120. (?, ?, ?, ?, ?);`
    121. stmt, err := db.Prepare(insertSQL)
    122. if err != nil {
    123. tx.Rollback()
    124. fmt.Printf("执行insertSQL失败,错误:%v\n", err)
    125. return
    126. }
    127. defer stmt.Close()
    128. result, err := stmt.Exec(like.Ip, like.Ua, like.Title, like.Hash, like.CreatedAt)
    129. if err != nil {
    130. tx.Rollback()
    131. fmt.Printf("执行insertSQL失败,错误:%v\n", err)
    132. return
    133. }
    134. id, err := result.LastInsertId()
    135. if err != nil {
    136. tx.Rollback()
    137. fmt.Printf("执行insertSQL失败,错误:%v\n", err)
    138. return
    139. }
    140. var like1 = &LikeInfo{
    141. ID: int(id),
    142. Ip: "127.0.0.1",
    143. Ua: "newUa",
    144. Title: "like you",
    145. Hash: 111,
    146. CreatedAt: time.Now(),
    147. }
    148. updateSQL := `UPDATE LikeInfo
    149. SET Ip = ?, Ua=?, Title = ?, Hash = ?, CreatedAt = ?
    150. WHERE ID = ?;`
    151. _, err = db.Exec(updateSQL, like1.Ip, like1.Ua, like1.Title, like1.Hash, like1.CreatedAt, like1.ID)
    152. if err != nil {
    153. tx.Rollback()
    154. fmt.Printf("执行updateSQL失败,错误:%v\n", err)
    155. return
    156. }
    157. //提交事务
    158. err = tx.Commit()
    159. if err != nil {
    160. tx.Rollback()
    161. fmt.Printf("提交失败,错误:%v\n", err)
    162. return
    163. }
    164. fmt.Println("事务执行成功")
    165. }

    sql:

    1. /*
    2. Navicat MySQL Data Transfer
    3. Source Server : localhost
    4. Source Server Version : 50733
    5. Source Host : localhost:3306
    6. Source Database : hello
    7. Target Server Type : MYSQL
    8. Target Server Version : 50733
    9. File Encoding : 65001
    10. Date: 2022-07-29 15:57:29
    11. */
    12. SET FOREIGN_KEY_CHECKS=0;
    13. -- ----------------------------
    14. -- Table structure for likeinfo
    15. -- ----------------------------
    16. DROP TABLE IF EXISTS `likeinfo`;
    17. CREATE TABLE `likeinfo` (
    18. `ID` int(11) NOT NULL AUTO_INCREMENT,
    19. `Ip` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
    20. `Ua` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
    21. `Title` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
    22. `Hash` int(11) DEFAULT NULL,
    23. `CreatedAt` datetime DEFAULT NULL,
    24. PRIMARY KEY (`ID`)
    25. ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    读取配置文件:

    1. package loadconfigs
    2. import (
    3. "encoding/json"
    4. "io/ioutil"
    5. "os"
    6. )
    7. //Conf 全局配置
    8. var Conf *Config
    9. //Redis 缓存配置
    10. type Redis struct {
    11. Host string `json:"host"`
    12. }
    13. //Db 数据库配置
    14. type Db struct {
    15. Type string `json:"type"`
    16. Write string `json:"write"`
    17. Read string `json:"read"`
    18. MaxOpenConns int `json:"maxOpenConns"`
    19. IdleConns int `json:"idleConns"`
    20. }
    21. //Config 全局配置文件
    22. type Config struct {
    23. Db Db `json:"db"`
    24. Redis Redis `json:"redis"`
    25. }
    26. func fileExists(filename string) bool {
    27. info, err := os.Stat(filename)
    28. if os.IsNotExist(err) {
    29. return false
    30. }
    31. return !info.IsDir()
    32. }
    33. //LoadConfig 加载配置
    34. func LoadConfig() error {
    35. var fileData []byte
    36. var err error
    37. if fileExists("app.json") { //先找当前目录
    38. fileData, err = ioutil.ReadFile("app.json")
    39. if err != nil {
    40. return err
    41. }
    42. } else {
    43. fileData, err = ioutil.ReadFile("lib/configs/app.json")
    44. if err != nil {
    45. return err
    46. }
    47. }
    48. Conf = &Config{}
    49. err = json.Unmarshal(fileData, Conf)
    50. return err
    51. }

  • 相关阅读:
    paper 阅读: An introduction to ROC analysis
    计算机二级WPS 选择题(模拟和解析十)
    SpringMVC的架构有什么优势?——表单和数据校验(四)
    skaffold提升K8s开发效率
    python+flask计算机毕业设计“研助乐”服务平台的设计与实现(程序+开题+论文)
    12_清醒思考艺术书摘
    多级菜单 树结构 排序 前端 后端 java
    金仓数据库KingbaseES安全指南--2.2. KingbaseES对数据库安全威胁的预防
    【Libevent】Libevent特征和事件集创建
    让你效率飞起的右键工具——超级右键
  • 原文地址:https://blog.csdn.net/IT_ziliang/article/details/126057845