{"id":208117,"date":"2025-07-08T12:43:21","date_gmt":"2025-07-08T04:43:21","guid":{"rendered":"https:\/\/server.hk\/cnblog\/208117\/"},"modified":"2025-07-08T12:43:21","modified_gmt":"2025-07-08T04:43:21","slug":"golang%e4%b8%admysql%e6%95%b0%e6%8d%ae%e5%ba%93%e5%87%ba%e9%94%99%e3%80%90sql-%e6%95%b0%e6%8d%ae%e5%ba%93%e5%b7%b2%e5%85%b3%e9%97%ad%e3%80%91","status":"publish","type":"post","link":"https:\/\/server.hk\/cnblog\/208117\/","title":{"rendered":"golang\u4e2dmysql\u6570\u636e\u5e93\u51fa\u9519\u3010sql: \u6570\u636e\u5e93\u5df2\u5173\u95ed\u3011"},"content":{"rendered":"<p><b><\/b> <\/p>\n<p>\u5f53\u524d\u4f4d\u7f6e\uff1a <span>&gt;<\/span> <span>&gt;<\/span> <span>&gt;<\/span> <span>&gt;<\/span> <span>golang\u4e2dmysql\u6570\u636e\u5e93\u51fa\u9519\u3010sql: \u6570\u636e\u5e93\u5df2\u5173\u95ed\u3011<\/span><\/p>\n<p><span>\u6765\u6e90\uff1astackoverflow<\/span><br \/>\n<span>2024-04-29 09:21:39<\/span><br \/>\n<span><i><\/i>0\u6d4f\u89c8<\/span><br \/>\n<span style=\"cursor: pointer\"><i><\/i>\u6536\u85cf<\/span> <\/p>\n<p>\u600e\u4e48\u5165\u95e8Golang\u7f16\u7a0b\uff1f\u9700\u8981\u5b66\u4e60\u54ea\u4e9b\u77e5\u8bc6\u70b9\uff1f\u8fd9\u662f\u65b0\u624b\u4eec\u521a\u63a5\u89e6\u7f16\u7a0b\u65f6\u5e38\u89c1\u7684\u95ee\u9898\uff1b\u4e0b\u9762\u5c31\u6765\u7ed9\u5927\u5bb6\u6574\u7406\u5206\u4eab\u4e00\u4e9b\u77e5\u8bc6\u70b9\uff0c\u5e0c\u671b\u80fd\u591f\u7ed9\u521d\u5b66\u8005\u4e00\u4e9b\u5e2e\u52a9\u3002\u672c\u7bc7\u6587\u7ae0\u5c31\u6765\u4ecb\u7ecd\u300agolang\u4e2dmysql\u6570\u636e\u5e93\u51fa\u9519\u3010sql: \u6570\u636e\u5e93\u5df2\u5173\u95ed\u3011\u300b\uff0c\u6d89\u53ca\u5230\uff0c\u6709\u9700\u8981\u7684\u53ef\u4ee5\u6536\u85cf\u4e00\u4e0b<\/p>\n<p> \u95ee\u9898\u5185\u5bb9<br \/>\n <\/p>\n<p>\u6211\u5c1d\u8bd5\u5728<code>golang<\/code>\u4e2d\u8bbe\u7f6emysql\u6570\u636e\u5e93\u3002<\/p>\n<p> \u6211\u521b\u5efa\u4e86 <code>db.go<\/code> \u7528\u4e8e mysql \u8bbe\u7f6e\u5e76\u5c06\u5176\u5bfc\u5165\u5230 <code>main.go<\/code>\u3002<\/p>\n<p> \u4f46\u662f\u5f53\u6211\u8fd0\u884c<code>main.go<\/code>\u65f6\uff0c\u7531\u4e8e<code>db.go<\/code>\u800c\u53d1\u751f\u9519\u8bef\u3002<\/p>\n<p> \u6211\u60f3\u89e3\u51b3\u8fd9\u4e2a\u9519\u8bef\u3002<\/p>\n<p>\u6ca1\u6709\u7f16\u8bd1\u9519\u8bef\u3002<\/p>\n<p> \u4f46\u662f\u5f53\u8fd0\u884c<code>go run main.go<\/code>\u65f6\uff0c\u51fa\u73b0\u9519\u8bef\u3002<\/p>\n<p>main.go<\/p>\n<pre>package main\n\n\/\/ import\n\nfunc main() {\n    err := godotenv.load()\n    if err != nil {\n    }\n    db := db.newdatabase(os.getenv(\"mysql_user\"), os.getenv(\"mysql_password\"), os.getenv(\"mysql_host\"))\n    s3 := s3.news3(os.getenv(\"aws_access_key_id\"), os.getenv(\"aws_secret_access_key\"))\n    dao := dao.newdao(db.database, s3)\n    service := service.newservice(dao)\n    cntlr := controller.newcontroller(service)\n\n    router := gin.default()\n\n    router.use(cors.new(cors.config{\n        alloworigins:     []string{\"*\"},\n        allowmethods:     []string{\"get\", \"post\", \"options\"},\n        allowheaders:     []string{\"content-type\", \"content-length\", \"accept-encoding\", \"x-csrf-token\", \"authorization\", \"accept\", \"origin\", \"cache-control\", \"x-requested-with\"},\n        exposeheaders:    []string{\"content-length\"},\n        allowcredentials: true,\n        alloworiginfunc: func(origin string) bool {\n            return true\n        },\n        maxage: 15 * time.second,\n    }))\n\n    api := router.group(\"\/api\")\n    {\n        api.get(\"\/articles\", func(c *gin.context) {\n            cntlr.getarticlecontroller(c)\n        })\n        api.get(\"\/article\/:id\", func(c *gin.context) {\n            cntlr.getsinglearticlecontroller(c)\n        })\n        api.get(\"\/delete\/:id\", func(c *gin.context) {\n            cntlr.deletearticlecontroller(c)\n        })\n        api.post(\"\/post\", func(c *gin.context) {\n            cntlr.postcontroller(c)\n        })\n        api.post(\"\/post\/image\", func(c *gin.context) {\n            cntlr.postimagecontroller(c)\n        })\n        api.post(\"\/post\/image\/db\", func(c *gin.context) {\n            cntlr.postimagetodbcontroller(c)\n        })\n    }\n\n    router.run(\":2345\")\n}\n\n<\/pre>\n<p>db.go<\/p>\n<pre>package db\n\nimport \"database\/sql\"\n\ntype database struct {\n    mysql_user     string\n    mysql_password string\n    mysql_host     string\n    database       *sql.db\n}\n\nfunc newdatabase(user, password, host string) *database {\n    db, err := sql.open(\"mysql\", user+\":\"+password+\"@tcp(\"+host+\":3306)\/article\")\n    if err != nil {\n        panic(err.error())\n    }\n\n    defer db.close()\n\n    err = db.ping()\n    if err != nil {\n        panic(err.error())\n    }\n\n    _, err = db.exec(\"create database if not exists article;\")\n    if err != nil {\n        panic(err)\n    }\n\n    _, err = db.exec(\"use article;\")\n    if err != nil {\n        panic(err)\n    }\n\n    _, err = db.exec(\"create table if not exists `articles` (`id` int not null auto_increment primary key,uuid varchar(36), `title` varchar(100) not null,`content` text not null ) engine=innodb default charset=utf8;\")\n    if err != nil {\n        panic(err)\n    }\n\n    _, err = db.exec(\"create table if not exists images (id int auto_increment not null primary key, article_uuid varchar(36), image_name varchar(50)); \")\n    if err != nil {\n        panic(err)\n    }\n    database := new(database)\n    database.database = db\n    return database\n}\n\n<\/pre>\n<p>\u8fd9\u91cc\u662f\u5b8c\u6574\u7684\u6e90\u4ee3\u7801\uff08\u5206\u652f\uff1arefactor-db\uff09\uff1a<\/p>\n<p> https:\/\/github.com\/jpskgc\/article\/tree\/refactor-db<\/p>\n<p>\u6211\u5e0c\u671b\u8fd0\u884c <code>go run main.go<\/code> \u65f6\u4e0d\u4f1a\u51fa\u73b0\u9519\u8bef\u3002<\/p>\n<p> \u4f46\u5b9e\u9645\u60c5\u51b5\u5e76\u975e\u5982\u6b64\u3002<\/p>\n<p> <code>db.go<\/code> \u5468\u56f4\u4f1a\u51fa\u73b0\u4e00\u4e9b\u95ee\u9898\u3002<\/p>\n<p>\u8fd9\u662f\u9519\u8bef\u6d88\u606f\u3002<\/p>\n<pre>GET \/api\/articles HTTP\/1.1\nHost: localhost:2345\nAccept: text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8,application\/signed-exchange;v=b3\nAccept-Encoding: gzip, deflate, br\nAccept-Language: en-US,en;q=0.9\nCache-Control: max-age=0\nConnection: keep-alive\nSec-Fetch-Mode: navigate\nSec-Fetch-Site: none\nSec-Fetch-User: ?1\nUpgrade-Insecure-Requests: 1\nUser-Agent: Mozilla\/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/76.0.3809.132 Safari\/537.36\n\n\nsql: database is closed\n\/Users\/jpskgc\/article\/api\/dao\/dao.go:36 (0x1553240)\n        (*Dao).GetArticleDao: panic(err.Error())\n\/Users\/jpskgc\/article\/api\/service\/service.go:34 (0x17a9abb)\n        Service.GetArticleService: results := s.dao.GetArticleDao()\n\/Users\/jpskgc\/article\/api\/controller\/controller.go:19 (0x17cd664)\n        Controller.GetArticleController: articles := controller.service.GetArticleService()\n\/Users\/jpskgc\/article\/api\/main.go:79 (0x17cec1f)\n        main.func2: cntlr.GetArticleController(c)\n\/Users\/jpskgc\/go\/pkg\/mod\/github.com\/gin-gonic\/[email&nbsp;protected]\/context.go:124 (0x1791e89)\n        (*Context).Next: c.handlers[c.index](c)\n\/Users\/jpskgc\/go\/pkg\/mod\/github.com\/gin-gonic\/[email&nbsp;protected]\/recovery.go:83 (0x17a5159)\n        RecoveryWithWriter.func1: c.Next()\n\/Users\/jpskgc\/go\/pkg\/mod\/github.com\/gin-gonic\/[email&nbsp;protected]\/context.go:124 (0x1791e89)\n        (*Context).Next: c.handlers[c.index](c)\n\/Users\/jpskgc\/go\/pkg\/mod\/github.com\/gin-gonic\/[email&nbsp;protected]\/logger.go:240 (0x17a4200)\n        LoggerWithConfig.func1: c.Next()\n\/Users\/jpskgc\/go\/pkg\/mod\/github.com\/gin-gonic\/[email&nbsp;protected]\/context.go:124 (0x1791e89)\n        (*Context).Next: c.handlers[c.index](c)\n\/Users\/jpskgc\/go\/pkg\/mod\/github.com\/gin-gonic\/[email&nbsp;protected]\/gin.go:389 (0x179b6a1)\n        (*Engine).handleHTTPRequest: c.Next()\n\/Users\/jpskgc\/go\/pkg\/mod\/github.com\/gin-gonic\/[email&nbsp;protected]\/gin.go:351 (0x179aed3)\n        (*Engine).ServeHTTP: engine.handleHTTPRequest(c)\n\/usr\/local\/go\/src\/net\/http\/server.go:2774 (0x12e2a07)\n        serverHandler.ServeHTTP: handler.ServeHTTP(rw, req)\n\/usr\/local\/go\/src\/net\/http\/server.go:1878 (0x12de5f0)\n        (*conn).serve: serverHandler{c.server}.ServeHTTP(w, w.req)\n\/usr\/local\/go\/src\/runtime\/asm_amd64.s:1337 (0x1059ea0)\n        goexit: BYTE    $0x90   \/\/ NOP\n\n[GIN] 2019\/09\/10 - 16:58:46 | 500 |    5.990926ms |             ::1 | GET      \/api\/articles<\/pre>\n<p> <\/p>\n<h2>\u89e3\u51b3\u65b9\u6848<\/h2>\n<p> <\/p>\n<p>\u53ea\u9700\u5220\u9664 <code>db.go<\/code> \u4e2d\u7684 <code>defer db.Close()<\/code> \u60a8\u9700\u8981\u5173\u95ed <code>NewDatabase<\/code> \u65b9\u6cd5\u7684\u8fde\u63a5<\/p>\n<p>\u4eca\u5929\u5173\u4e8e\u300agolang\u4e2dmysql\u6570\u636e\u5e93\u51fa\u9519\u3010sql: \u6570\u636e\u5e93\u5df2\u5173\u95ed\u3011\u300b\u7684\u5185\u5bb9\u4ecb\u7ecd\u5c31\u5230\u6b64\u7ed3\u675f\uff0c\u5982\u679c\u6709\u4ec0\u4e48\u7591\u95ee\u6216\u8005\u5efa\u8bae\uff0c\u53ef\u4ee5\u5728\u516c\u4f17\u53f7\u4e0b\u591a\u591a\u56de\u590d\u4ea4\u6d41\uff1b\u6587\u4e2d\u82e5\u6709\u4e0d\u6b63\u4e4b\u5904\uff0c\u4e5f\u5e0c\u671b\u56de\u590d\u7559\u8a00\u4ee5\u544a\u77e5\uff01<\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u5f53\u524d\u4f4d\u7f6e\uff1a &gt; &gt; &#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4925],"tags":[],"class_list":["post-208117","post","type-post","status-publish","format-standard","hentry","category-4925"],"_links":{"self":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/posts\/208117","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/comments?post=208117"}],"version-history":[{"count":0,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/posts\/208117\/revisions"}],"wp:attachment":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/media?parent=208117"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/categories?post=208117"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/tags?post=208117"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}