1、安装驱动
| go get github.com/go-sql-driver/mysql |
2、导入需要的库
| import ( |
| "database/sql" |
| "fmt" |
| _ "github.com/go-sql-driver/mysql" |
| ) |
3、连接数据库
| func main() { |
| |
| db, _ := sql.Open("mysql", "root:123456@(localhost)/world") |
| defer db.Close() |
| err := db.Ping() |
| if err != nil { |
| fmt.Println("数据库连接失败") |
| return |
| } else { |
| fmt.Println("数据库连接成功") |
| } |
| } |
4、查询表
| rows, _ := db.Query("select * from city") |
| var ID, Population int |
| var Name, CountryCode, District string |
| for rows.Next() { |
| rows.Scan(&ID, &Name, &CountryCode, &District, &Population) |
| fmt.Println(ID, "--", Name, "--", CountryCode, "--", District, "--", Population) |
| } |
查询截图:

5、全部代码
| package main |
| |
| import ( |
| "database/sql" |
| "fmt" |
| _ "github.com/go-sql-driver/mysql" |
| ) |
| |
| func main() { |
| |
| db, _ := sql.Open("mysql", "root:123456@(localhost)/world") |
| defer db.Close() |
| err := db.Ping() |
| if err != nil { |
| fmt.Println("数据库连接失败") |
| return |
| } else { |
| fmt.Println("数据库连接成功") |
| } |
| |
| |
| rows, _ := db.Query("select * from city") |
| var ID, Population int |
| var Name, CountryCode, District string |
| for rows.Next() { |
| rows.Scan(&ID, &Name, &CountryCode, &District, &Population) |
| fmt.Println(ID, "--", Name, "--", CountryCode, "--", District, "--", Population) |
| } |
| } |
6、拓展
| |
| |
| sql:="insert into stu values (2,'berry')" |
| result,_:=db.Exec(sql) |
| n,_:=result.RowsAffected(); |
| fmt.Println("受影响的记录数是",n) |
| |
| |
| |
| stu:=[2][2] string{{"3","ketty"},{"4","rose"}} |
| stmt,_:=db.Prepare("insert into stu values (?,?)") |
| for _,s:=range stu{ |
| stmt.Exec(s[0],s[1]) |
| } |
| |
| |
| |
| var id,name string |
| rows:=db.QueryRow("select * from stu where id=4") |
| rows.Scan(&id,&name) |
| fmt.Println(id,"--",name) |
本文作者:Dancing-Pierre
本文链接:https://www.cnblogs.com/wyc-1009/p/17548174.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步