热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

UsingGowithMariaDB_MySQL

UsingGowithMariaDB
MariaDB

I have been using Google’s Go programming language for a couple of years and basically fell in love with it. About a year ago I started using it for almost all of my MariaDB and MySQL development, and pretty much everything I do unless it involves the python pandas library (a subject for a separate blog, perhaps).

While I could gush endlessly about Go (golang), the documentation sums things up quite nicely: “Go is expressive, concise, clean, and efficient. Its concurrency mechanisms make it easy to write programs that get the most out of multicore and networked machines, while its novel type system enables flexible and modular program construction. Go compiles quickly to machine code yet has the convenience of garbage collection and the power of run-time reflection. It's a fast, statically typed, compiled language that feels like a dynamically typed, interpreted language.”

I won’t delve deeply into the language. Do pleaseread more about it here.

For MariaDB and MySQL development, I currently use theGo-MySQL-Driver found here.

If you already have Go installed, you can easily fetch that library with “go get”:

go get github.com/go-sql-driver/mysql

Let’s look at a (very) simple program demonstrating usage, and find out whether the driver supports MariaDB 10. Pardon me for stripping out the error handling:

skysql:dellis$ cat gomaria.gopackage mainimport (	"fmt"	"database/sql"	_ "github.com/go-sql-driver/mysql")func main() {	// Create the database handle, confirm driver is present	db, _ := sql.Open("mysql", "dellis:@/shud")	defer db.Close()	// Connect and check the server version	var version string	db.QueryRow("SELECT VERSION()").Scan(&version)	fmt.Println("Connected to:", version)}skysql:dellis$ go build gomaria.goskysql:dellis$ ./gomariaConnected to: 10.0.11-MariaDB

Success!

One thing of interest is that the variable “db” references a database handle, rather than an actual connection to the database server. In the example above, a connection to the database isn’t actually created until we call db.QueryRow().

I have not explicitly opened or closed an inpidual connection in this example, because Go’s SQL package automatically handles connection pooling. Let’s give that a (very silly) test, again stripping out the error handling:

skysql:dellis$ cat gomaria.gopackage mainimport (	"sync"	"database/sql"	_ "github.com/go-sql-driver/mysql")func main() {	// Create the database handle, confirm driver is present	db, _ := sql.Open("mysql", "dellis:@/shud")	defer db.Close()	// Test several connections	var wg sync.WaitGroup	for i := 0; i <10; i++ {		wg.Add(1)		go func(db *sql.DB) {		 defer wg.Done()		 var result string		 db.QueryRow("SELECT SLEEP(10)").Scan(&result)		 }(db)	}	wg.Wait()}

In theory, then, this will create ten goroutines (like and unlike threads, or, again quoting the documentation, “a function executing concurrently with other goroutines in the same address space”, which are multiplexed onto multiple system threads), each of which will try to connect to MariaDB and execute SELECT SLEEP(10). The main() function will wait until each of these has completed (via sync.WaitGroup), giving me time to check the processlist to see what happened.

Notice that I pass the database handle to my function but once again do not explicitly open or close connections.

Let’s try it:

skysql:dellis$ ./gomariaMariaDB [shud]> SHOW PROCESSLIST;+----+--------+-----------------+------+---------+------+------------+------------------+----------+| Id | User | Host| db | Command | Time | State| Info | Progress |+----+--------+-----------------+------+---------+------+------------+------------------+----------+|3 | dellis | localhost:57547 | shud | Query |3 | User sleep | SELECT SLEEP(10) |0.000 ||4 | dellis | localhost:57548 | shud | Query |3 | User sleep | SELECT SLEEP(10) |0.000 ||5 | dellis | localhost:57549 | shud | Query |3 | User sleep | SELECT SLEEP(10) |0.000 ||6 | dellis | localhost:57550 | shud | Query |3 | User sleep | SELECT SLEEP(10) |0.000 ||7 | dellis | localhost:57551 | shud | Query |3 | User sleep | SELECT SLEEP(10) |0.000 ||8 | dellis | localhost:57552 | shud | Query |3 | User sleep | SELECT SLEEP(10) |0.000 ||9 | dellis | localhost:57553 | shud | Query |3 | User sleep | SELECT SLEEP(10) |0.000 || 10 | dellis | localhost:57554 | shud | Query |3 | User sleep | SELECT SLEEP(10) |0.000 || 11 | dellis | localhost:57555 | shud | Query |3 | User sleep | SELECT SLEEP(10) |0.000 || 12 | dellis | localhost:57556 | shud | Query |3 | User sleep | SELECT SLEEP(10) |0.000 || 13 | dellis | localhost | shud | Query |0 | init | SHOW PROCESSLIST |0.000 |+----+--------+-----------------+------+---------+------+------------+------------------+----------+

And again: Success! We opened ten connections, and each of those issued their queries, with the main() function awaiting completion.

If you were to “sleep” this program with time.Sleep() after the goroutines complete, you might see some idle connections to the database remaining, held open by the connection pool. That can be controlled via db.SetMaxIdleConns() and db.SetMaxOpenConns().

There is a lot more to the topic of using MariaDB and MySQL with Go, and if you are interested I recommend visitingVividCortex’s tutorial available here. The site covers a lot of ground, including some of the limitations you may encounter. It is a great place to start.

With a language so very well designed for concurrency, it may be interesting to see whether the Go MySQL driver could take advantage of MariaDB’s non-blocking API as we see in the mariasql binding for Node.js, but that goes well beyond my subject today.

Thanks for reading.

推荐阅读
  • 如何利用 Myflash 解析 binlog ?
    本文主要介绍了对Myflash的测试,从准备测试环境到利用Myflash解析binl ... [详细]
  • 微软头条实习生分享深度学习自学指南
    本文介绍了一位微软头条实习生自学深度学习的经验分享,包括学习资源推荐、重要基础知识的学习要点等。作者强调了学好Python和数学基础的重要性,并提供了一些建议。 ... [详细]
  • PDO MySQL
    PDOMySQL如果文章有成千上万篇,该怎样保存?数据保存有多种方式,比如单机文件、单机数据库(SQLite)、网络数据库(MySQL、MariaDB)等等。根据项目来选择,做We ... [详细]
  • 这篇文章给大家介绍怎么从源码启动和编译IoTSharp ,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。IoTSharp项目是 ... [详细]
  • JavaScript和Python是用于构建各种应用程序的两种有影响力的编程语言。尽管JavaScript多年来一直是占主导地位的编程语言,但Python的迅猛发展有 ... [详细]
  • 这么多流媒体服务器?你怎么技术选型?
    在上一篇文章里我们介绍了我们介绍了MCU和SFU的优缺点,webRTC通信方案SFU和MCU的区别?下面就来探讨下常见的SFU开源解决方案,当然,你也可以自己实现SFU流媒体服务器 ... [详细]
  • shell脚本实战 pdf_Shell 脚本操作数据库实战
    安装mariadb数据库(默认没有密码,直接mysql即可进入数据库管理控制台)yuminstallmariadbmariadb-serv ... [详细]
  • MFC程序连接MySQL成功实现查询功能,但无法实现修改操作——详解查询语句在MySQL中的使用过程
    selectxxx,xxx,xxxfromxxxwherexxxxxx,xxxxxx程序的日常开发中,我们经常会写到各种各样的简单的,复杂的查询sql语 ... [详细]
  • 数据库进入全新时代,腾讯云发布五大数据库提前布局
    8月28日,腾讯云数据库在京正式启动战略升级,宣布未来将聚焦云原生、自治、超融合三大战略方向,以用户为中心,联接未来。并在现场面向全球用户同步发布五大战略级新品,包括数据库智能管家 ... [详细]
  • 使用Node.js进行数据库操作和身份认证的方法:Session和JWT
    文章目录数据库和身份认证Node操作mysql配置mysql模块操作mysql数据库Web开发模式服务端渲染前后端分离如何选择身份认证Session认证机制Session工作原理E ... [详细]
  • Google Play推出全新的应用内评价API,帮助开发者获取更多优质用户反馈。用户每天在Google Play上发表数百万条评论,这有助于开发者了解用户喜好和改进需求。开发者可以选择在适当的时间请求用户撰写评论,以获得全面而有用的反馈。全新应用内评价功能让用户无需返回应用详情页面即可发表评论,提升用户体验。 ... [详细]
  • Python正则表达式学习记录及常用方法
    本文记录了学习Python正则表达式的过程,介绍了re模块的常用方法re.search,并解释了rawstring的作用。正则表达式是一种方便检查字符串匹配模式的工具,通过本文的学习可以掌握Python中使用正则表达式的基本方法。 ... [详细]
  • 本文介绍了通过mysql命令查看mysql的安装路径的方法,提供了相应的sql语句,并希望对读者有参考价值。 ... [详细]
  • Oracle10g备份导入的方法及注意事项
    本文介绍了使用Oracle10g进行备份导入的方法及相关注意事项,同时还介绍了2019年独角兽企业重金招聘Python工程师的标准。内容包括导出exp命令、删用户、创建数据库、授权等操作,以及导入imp命令的使用。详细介绍了导入时的参数设置,如full、ignore、buffer、commit、feedback等。转载来源于https://my.oschina.net/u/1767754/blog/377593。 ... [详细]
  • RN即ReactNative基于React框架针对移动端的跨平台框架,在学习RN前建议最好熟悉下html,css,js,当然如果比较急,那就直接上手吧,毕竟用学习前面基础的时间,R ... [详细]
author-avatar
跌蕩起伏的2012_900
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有