Golang operation Database already has the existing library "Database/sql" can be used, but "Database/sql" only provides the most basic operation interface;
For a table in the database and other operations, such as adding and deleting, you must manually write SQL string, which is usually a write dead character string (Hard-code),
And you need to manually maintain the mapping of the fields in SQL to the variables in the Golang, which is poor extensibility and very error-prone.
Typically, we expect a struct in Golang to establish a mapping relationship with a table in db (Mapper),
We then manipulate the corresponding table in the DB by manipulating the struct, without hard-coded SQL string, without having to maintain the field mappings manually.
Sqlmapper is such a minimalist tool library (as simple as a go file).
Original address: Https://github.com/arthas29/sqlmapper
For example, there is a table in db with the following structure:
CREATE TABLE' test_table ' (' Field_key ' )varchar( -) not NULL DEFAULT "', ' Field_one 'varchar( -)DEFAULT NULL, ' Field_two 'tinyint(1)DEFAULT NULL, ' Field_thr 'int( A)DEFAULT NULL, ' Field_fou 'float DEFAULT NULL, PRIMARY KEY(' Field_key ')) ENGINE=InnoDBDEFAULTCHARSET=UTF8;
In Golang, create the corresponding struct, as follows:
// struct in Golang such as: type demorow struct { fieldkey string ' sql:' field_key '' FieldOne string ' sql:' Field_one "' fieldtwo bool ' sql:" field_two "' fieldthr int64 ' sql:" field_ Thr "' fieldfou float64 ' sql:" Field_fou "'}
Then, we can execute///operate through this struct SELECT
INSERT
UPDATE
DELETE
, without hard coding the lengthy SQL string;
Example (see fields_map_test.go for more examples):
//Select Single Row//Query by primary KEY (Field[0])Func Querybykey (CTX context. Context, TX *sql. TX, DB *SQL. DB, Fieldkey string) (*Demorow, error) { varrow Demorow row. Fieldkey=Fieldkey FM, err:= Newfieldsmap (table, &row)ifErr! =Nil {returnnil, err} objptr, err:=FM. Sqlselectbyprikey (CTX, TX, DB)ifErr! =Nil {returnnil, err}returnObjPtr. (*demorow), nil}
Table fields in Golang and DB are automatically mapped by reflection-Sqlmapper