2021-10-09 来源:华纳网 责任编辑:韩玉玲 人气:
核心提示:用Go实现一个MySQL简易服务器

知识点:

用Go实现一个MySQL简易服务器
 


 

本课内容:

大家好,欢迎来到谷雨课堂,

MySQL是使用量非常多的数据库,

我们今天来用Go来实现一台MySQL数据库,

没错,真是MySQL数据库,

不过暂时没有做后端存储,

数据都是存储在内存里的,

不过SQL语句的解析等都是全功能的,

各种客户端也可以连接。

 

通过这个数据库,

对于我们学习MySQL的通信是非常有用的

 

以下是全部代码:

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
package mainimport (  "time"
  sqle "github.com/dolthub/go-mysql-server"  "github.com/dolthub/go-mysql-server/auth"  "github.com/dolthub/go-mysql-server/memory"  "github.com/dolthub/go-mysql-server/server"  "github.com/dolthub/go-mysql-server/sql"  "github.com/dolthub/go-mysql-server/sql/information_schema")
func main() {  engine := sqle.NewDefault()  engine.AddDatabase(createTestDatabase())  engine.AddDatabase(information_schema.NewInformationSchemaDatabase(engine.Catalog))
  config := server.Config{    Protocol: "tcp",    Address:  "localhost:3307",    Auth:     auth.NewNativeSingle("root", "123456", auth.AllPermissions),  }
  s, err := server.NewDefaultServer(config, engine)  if err != nil {    panic(err)  }
  s.Start()}
func createTestDatabase() *memory.Database {  const (    dbName    = "mydb"    tableName = "mytable"  )
  db := memory.NewDatabase(dbName)  table := memory.NewTable(tableName, sql.Schema{    {Name: "name", Type: sql.Text, Nullable: false, Source: tableName},    {Name: "email", Type: sql.Text, Nullable: false, Source: tableName},    {Name: "phone_numbers", Type: sql.JSON, Nullable: false, Source: tableName},    {Name: "created_at", Type: sql.Timestamp, Nullable: false, Source: tableName},  })
  db.AddTable(tableName, table)  ctx := sql.NewEmptyContext()  table.Insert(ctx, sql.NewRow("John Doe", "john@doe.com", []string{"555-555-555"}, time.Now()))  table.Insert(ctx, sql.NewRow("John Doe", "johnalt@doe.com", []string{}, time.Now()))  table.Insert(ctx, sql.NewRow("Jane Doe", "jane@doe.com", []string{}, time.Now()))  table.Insert(ctx, sql.NewRow("Evil Bob", "evilbob@gmail.com", []string{"555-666-555", "666-666-666"}, time.Now()))  return db}

 

完整的源代码可以登录【华纳网】下载。

https://www.worldwarner.com/




 





免责声明:本文仅代表作者个人观点,与华纳网无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。