go-mysql,一个易用的mysql接口框架实现_MySQL
介绍
go-mysql是一个用go写的mysql driver,使用接口类似于go自身的database sql,但是稍微有一点不同,现阶段还不支持集成进go database/sql中,但实现难度并不大,后续可能会接入。
go-mysql最先开始于mixer(一个用go实现的mysql proxy)中,随着mixer的演化,我觉得有必要将其mysql模块独立出来使用。对于mixer,后续我会详细介绍。
为什么要自己实现一套新的接口,而不是go自身的sql接口呢?最主要的原因在于我很不习惯使用Query的查询方式。go自身的query例子:
<code>age := 27rows, err := db.Query("SELECT name FROM users WHERE age=?", age)if err != nil { log.Fatal(err)}for rows.Next() { var name string if err := rows.Scan(&name); err != nil { log.Fatal(err) } fmt.Printf("%s is %d/n", name, age)}if err := rows.Err(); err != nil { log.Fatal(err)}</code>
可以看到,使用起来非常的繁琐复杂,如果代码里面select语句很多(恰恰我们代码里面n多select),那么如果每次select都要靠这种方式得到我们需要的结果,那我可能写代码会写崩溃的。所以势必我们需要提供一套封装用来简化select的结果集获取。
Resultset
go-mysql跟go自身的sql接口最大的不一样在于Query的时候直接返回了一个resultset,而这个resultset定义如下:
<code>type Field struct { Name []byte Type uint8 Flag uint16}type Resultset struct { Status uint16 //server status for this query resultset Fields []Field FieldNames map[string]int Data [][]interface{}}</code>
Field用来表示查询的时候返回的数据每列的名字,数据类型以及一些特定的Flag。而resultset中的Data则是存放了query结果中对于的实际数据。因为对于mysql select来说,它返回的是一个"m x n"的结果集,我们直接使用[][]interface{}在go中表示。
Resultset提供了非常方便的接口用于select数据的获取:
<code>//指定某一行,某一列获取数据,结果为stringfunc (r *Resultset) GetString(row, column int) (string, error)//执行某一行,某一列的名字获取数据,结果为stringfunc (r *Resultset) GetStringByName(row int, columnName int) (string, error)</code>
接口
go-mysql除了query之外,几乎提供了与go database/sql一样的接口使用方式:
<code>//创建一个db,最大允许保活16个空闲连接//dsn格式为:<username>:<password>@<host>:<port>/<database>db := NewDB("qing:admin@127.0.0.1:3306/mixer", 16)//ping一下,看mysql server是不是还是活的db.Ping()//执行exec,包括insert,update,delete,replacer, err := db.Exec("insert into mixer_conn (id, str) values (1, `abc`)")println(r.LastInsertId(), r.RowsAffected())//执行exec,语句中包含 ?占位符,需要传递相应的参数r, err := db.Exec("insert into mixer_conn (id, str) values (?, ?)", 2, "efg")println(r.LastInsertId(), r.RowsAffected())//执行select,得到结果集,并获取相关数据r, err := db.Query("select str from mixer_conn where id = 1")str, _ = r.GetString(0, 0)str, _ = r.GetStringByName(0, "str")//开始一个事物tx, err = db.Begin()//在事物里面执行语句tx.Exec("insert into mixer_conn (id, str) values (3, `abc`)")//提交事物tx.Commit()//创建一个prepare statements, err := db.Prepare("insert into mixer_conn (id, str) values(?, ?)")//执行 prepare statements.Exec(5, "abc")//关闭 prepare statements.Close()</database></port></host></password></username></code>
不光如此,go-mysql还提供单独获取一个conn,用于给外部额外使用的功能,譬如:
<code>conn, err := db.GetConn()//我需要设置conn的字符集为gb2312conn.SetCharset("gb2312") conn.Close()</code>
可以看到,go-mysql的使用非常简单,现阶段正逐渐在我们项目中使用,也非常期待您的反馈。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Full table scanning may be faster in MySQL than using indexes. Specific cases include: 1) the data volume is small; 2) when the query returns a large amount of data; 3) when the index column is not highly selective; 4) when the complex query. By analyzing query plans, optimizing indexes, avoiding over-index and regularly maintaining tables, you can make the best choices in practical applications.

Yes, MySQL can be installed on Windows 7, and although Microsoft has stopped supporting Windows 7, MySQL is still compatible with it. However, the following points should be noted during the installation process: Download the MySQL installer for Windows. Select the appropriate version of MySQL (community or enterprise). Select the appropriate installation directory and character set during the installation process. Set the root user password and keep it properly. Connect to the database for testing. Note the compatibility and security issues on Windows 7, and it is recommended to upgrade to a supported operating system.

InnoDB's full-text search capabilities are very powerful, which can significantly improve database query efficiency and ability to process large amounts of text data. 1) InnoDB implements full-text search through inverted indexing, supporting basic and advanced search queries. 2) Use MATCH and AGAINST keywords to search, support Boolean mode and phrase search. 3) Optimization methods include using word segmentation technology, periodic rebuilding of indexes and adjusting cache size to improve performance and accuracy.

The difference between clustered index and non-clustered index is: 1. Clustered index stores data rows in the index structure, which is suitable for querying by primary key and range. 2. The non-clustered index stores index key values and pointers to data rows, and is suitable for non-primary key column queries.

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

In MySQL database, the relationship between the user and the database is defined by permissions and tables. The user has a username and password to access the database. Permissions are granted through the GRANT command, while the table is created by the CREATE TABLE command. To establish a relationship between a user and a database, you need to create a database, create a user, and then grant permissions.

MySQL and MariaDB can coexist, but need to be configured with caution. The key is to allocate different port numbers and data directories to each database, and adjust parameters such as memory allocation and cache size. Connection pooling, application configuration, and version differences also need to be considered and need to be carefully tested and planned to avoid pitfalls. Running two databases simultaneously can cause performance problems in situations where resources are limited.

MySQL supports four index types: B-Tree, Hash, Full-text, and Spatial. 1.B-Tree index is suitable for equal value search, range query and sorting. 2. Hash index is suitable for equal value searches, but does not support range query and sorting. 3. Full-text index is used for full-text search and is suitable for processing large amounts of text data. 4. Spatial index is used for geospatial data query and is suitable for GIS applications.
