Go基于sqlx实现的sql增删改查的工具类

这篇具有很好参考价值的文章主要介绍了Go基于sqlx实现的sql增删改查的工具类。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1、驱动下载

sqlx是Go语言内置database/sql的扩展包,它在内置database/sql基础上提供更简洁的数据库操作。
GitHub地址:https://github.com/jmoiron/sqlx
API文档:https://pkg.go.dev/github.com/jmoiron/sqlx
用例文档http://jmoiron.github.io/sqlx/

1.1、依赖安装

依赖包安装命令

go get github.com/jmoiron/sqlx

1.2、SQL数据库驱动包列表

go驱动包列表https://github.com/golang/go/wiki/SQLDrivers。

database/sql和database/sql/driver包分别用于使用Go中的数据库和实现数据库驱动程序。
Go的sql包的驱动程序包括:

  • Amazon AWS Athena: https://github.com/uber/athenadriver
  • AWS Athena: https://github.com/segmentio/go-athena
  • AWS DynamoDB: https://github.com/btnguyen2k/godynamo
  • Apache Avatica/Phoenix: https://github.com/apache/calcite-avatica-go
  • Apache H2: https://github.com/jmrobles/h2go
  • Apache Hive: https://github.com/sql-machine-learning/gohive
  • Apache Ignite/GridGain: https://github.com/amsokol/ignite-go-client
  • Apache Impala: https://github.com/bippio/go-impala
  • Azure Cosmos DB: https://github.com/btnguyen2k/gocosmos
  • ClickHouse (uses HTTP API): https://github.com/mailru/go-clickhouse
  • ClickHouse (uses native TCP interface): https://github.com/ClickHouse/clickhouse-go
  • CockroachDB: Use any PostgreSQL driver
  • Couchbase N1QL: https://github.com/couchbase/go_n1ql
  • DB2 LUW (uses cgo): https://github.com/asifjalil/cli
  • DB2 LUW and DB2/Z with DB2-Connect: https://bitbucket.org/phiggins/db2cli (Last updated 2015-08)
  • DB2 LUW, z/OS, iSeries and Informix: https://github.com/ibmdb/go_ibm_db
  • Databricks: https://github.com/databricks/databricks-sql-go
  • DuckDB: https://github.com/marcboeker/go-duckdb
  • Exasol: (pure Go): https://github.com/exasol/exasol-driver-go
  • Firebird SQL: https://github.com/nakagami/firebirdsql
  • Genji (pure go): https://github.com/genjidb/genji
  • Google Cloud BigQuery: https://github.com/solcates/go-sql-bigquery
  • Google Cloud Spanner: https://github.com/googleapis/go-sql-spanner
  • Google Cloud Spanner: https://github.com/rakyll/go-sql-driver-spanner
  • MS ADODB: https://github.com/mattn/go-adodb
  • MS SQL Server (pure go): https://github.com/microsoft/go-mssqldb
  • MS SQL Server (uses cgo): https://github.com/minus5/gofreetds
  • MaxCompute: https://github.com/sql-machine-learning/gomaxcompute
  • MySQL: https://github.com/go-sql-driver/mysql/ [*]
  • MySQL: https://github.com/siddontang/go-mysql/ [**] (also handles replication)
  • MySQL: https://github.com/ziutek/mymysql [*]
  • ODBC: https://bitbucket.org/miquella/mgodbc (Last updated 2016-02)
  • ODBC: https://github.com/alexbrainman/odbc
  • Oracle (pure go): https://github.com/sijms/go-ora
  • Oracle (uses cgo): https://github.com/godror/godror
  • Oracle (uses cgo): https://github.com/mattn/go-oci8
  • Oracle (uses cgo): https://gopkg.in/rana/ora.v4
  • Postgres (pure Go): https://github.com/jackc/pgx [*]
  • Postgres (pure Go): https://github.com/lib/pq [*]
  • Postgres (uses cgo): https://github.com/jbarham/gopgsqldriver
  • Presto: https://github.com/prestodb/presto-go-client
  • QL: https://pkg.go.dev/modernc.org/ql
  • SAP ASE (pure go): https://github.com/SAP/go-ase
  • SAP ASE (uses cgo): https://github.com/SAP/cgo-ase
  • SAP HANA (pure go): https://github.com/SAP/go-hdb
  • SAP HANA (uses cgo): https://help.sap.com/viewer/0eec0d68141541d1b07893a39944924e/2.0.03/en-US/0ffbe86c9d9f44338441829c6bee15e6.html
  • SQL over REST: https://github.com/adaptant-labs/go-sql-rest-driver
  • SQLite (uses cgo): https://github.com/gwenn/gosqlite - Supports SQLite dynamic data typing
  • SQLite (uses cgo): https://github.com/mattn/go-sqlite3 [*]
  • SQLite (uses cgo): https://github.com/mxk/go-sqlite
  • SQLite: (pure go): https://modernc.org/sqlite
  • SQLite: (uses cgo): https://github.com/rsc/sqlite
  • SingleStore: Use any MySQL driver
  • Snowflake (pure Go): https://github.com/snowflakedb/gosnowflake
  • Sybase ASE (pure go): https://github.com/thda/tds
  • Sybase SQL Anywhere: https://github.com/a-palchikov/sqlago
  • TiDB: Use any MySQL driver
  • Vertica: https://github.com/vertica/vertica-sql-go
  • Vitess: https://pkg.go.dev/vitess.io/vitess/go/vt/vitessdriver
  • YDB (pure go): https://github.com/ydb-platform/ydb-go-sdk
  • YQL (Yahoo! Query Language): https://github.com/mattn/go-yql

标有[*]的驱动程序都包含在https://github.com/bradfitz/go-sql-test的兼容性测试套件中并通过了该测试套件。
标记为[**]的驱动程序通过兼容性测试套件,但当前未包含在其中。

2、实现代码

2.1 sql工具类代码

例子使用了mysql驱动
封装的工具类sqldao.go文章来源地址https://www.toymoban.com/news/detail-639733.html

package dao

import (
	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
)

type SqlDao struct {
	db        *sqlx.DB
	tx        *sqlx.Tx
	Driver    string
	Dsn       string
	OpenConns int
	IdleConns int
}

func (dao *SqlDao) Connect() (err error) {
	dao.db, err = sqlx.Connect(dao.Driver, dao.Dsn)
	if err == nil {
		if dao.OpenConns > 0 {
			dao.db.SetMaxOpenConns(20)
		}
		if dao.IdleConns > 0 {
			dao.db.SetMaxIdleConns(20)
		}
	}
	return err
}
func (dao *SqlDao) Close() {
	dao.db.Close()
}
func (dao *SqlDao) InsertOne(sql string, args ...any) (int64, error) {
	result, err := dao.db.Exec(sql, args...)
	if err == nil {
		tid, err := result.LastInsertId()
		return tid, err
	}
	return 0, err
}

func (dao *SqlDao) InsertOneObj(sql string, obj interface{}) (int64, error) {
	result, err := dao.db.NamedExec(sql, obj)
	if err == nil {
		id, err := result.LastInsertId()
		return id, err
	}
	return 0, err
}

// 批量插入
// return int64,error 插入成功数量,错误
func (dao *SqlDao) InsertManyObj(sql string, objs []interface{}) (int64, error) {
	result, err := dao.db.NamedExec(sql, objs)
	if err == nil {
		count, err := result.RowsAffected()
		return count, err
	}
	return 0, err
}

func (dao *SqlDao) FindOne(model any, sql string, args ...interface{}) error {
	err := dao.db.Get(model, sql, args...)
	return err
}

func (dao *SqlDao) FindMany(model any, sql string, args ...interface{}) error {
	err := dao.db.Select(model, sql, args...)
	return err
}

// 更新数据
func (dao *SqlDao) Update(sql string, args ...any) (int64, error) {
	ret, err := dao.db.Exec(sql, args...)
	if err == nil {
		n, err := ret.RowsAffected()
		return n, err
	}
	return 0, err
}

// 删除数据
func (dao *SqlDao) Delete(sql string, args ...any) (int64, error) {
	ret, err := dao.db.Exec(sql, args...)
	if err == nil {
		n, err := ret.RowsAffected()
		return n, err
	}
	return 0, err
}

// 开启事务
func (dao *SqlDao) Beginx() (*sqlx.Tx, error) {
	var err error
	dao.tx, err = dao.db.Beginx() // 开启事务
	return dao.tx, err
}

// 事务回滚
func (dao *SqlDao) Rollback() error {
	return dao.tx.Rollback()
}

// 事务提交
func (dao *SqlDao) Commit() error {
	return dao.tx.Commit()
}

2.2 使用例子

package main

import (
	"fmt"
	"log"
	"mydb/dao"
	"strconv"
	"time"
)

/*
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(100) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
*/

type User struct {
	Id   int64  `sql:"id"`
	Name string `sql:"name"`
	Age  int    `sql:"age"`
}

func (s User) String() string {
	return fmt.Sprintf("%v %v %v", s.Id, s.Name, s.Age)
}
func main() {
	dao := dao.SqlDao{
		Driver: "mysql",
		Dsn:    "root:peng123@tcp(127.0.0.1:3306)/gotest?charset=utf8mb4&parseTime=True&loc=Asia%2fShanghai",
	}
	err := dao.Connect()
	if err != nil {
		log.Fatalln("connect error====")
	}
	defer dao.Close()

	insertId1, err1 := dao.InsertOne("insert into user(name, age) values(?,?)", "stu1", 11)
	fmt.Printf("insert sql insertId:%v,%v\n", insertId1, err1)

	dao.InsertOneObj("insert into user(name, age) values(:name,:age)", User{Name: "stu2", Age: 67})

	users := []interface{}{
		User{Name: "stu9", Age: 20},
		User{Name: "stu10", Age: 21},
	}
	rowsAffected, err2 := dao.InsertManyObj("insert into user(name,age) values(:name,:age)", users)
	fmt.Printf("======InsertObj2:%v,%v\n", rowsAffected, err2)

	var user3 User
	dao.FindOne(&user3, "select * from user where name=?", "stu1")
	fmt.Printf("======FindOne:%v\n", user3)

	var user4 []User
	dao.FindMany(&user4, "select * from user where age < ?", 5)
	for index, u := range user4 {
		fmt.Printf("======FindMany:%v, %v\n", index, u)
	}

	rowsAffected5, err5 := dao.Update("update user set age=? where id=?", 25, 1)
	fmt.Printf("======Update:%v,%v\n", rowsAffected5, err5)

	rowsAffected6, err6 := dao.Delete("delete from user where age=?", 11)
	fmt.Printf("======Delete:%v,%v\n", rowsAffected6, err6)

	dao.Beginx()
	for i := 0; i <= 400000; i++ {
		dao.InsertOneObj("insert into user(name, age) values(:name,:age)", User{Name: "stu" + strconv.Itoa(i), Age: i})
		if i != 0 && i%10000 == 0 {
			time.Sleep(time.Duration(1) * time.Second)
			err = dao.Commit()
			fmt.Printf("======Commit i:%v, %v\n", i, err)
			dao.Beginx()
		}
	}
}

2.3 运行效果

D:\project\go\gotest\sql>go run main.go
insert sql insertId:1,<nil>
======InsertObj2:2,<nil>
======FindOne:1 stu1 11
======Update:1,<nil>
======Delete:0,<nil>
======Commit i:10000, <nil>
======Commit i:20000, <nil>
======Commit i:30000, <nil>
======Commit i:40000, <nil>
======Commit i:50000, <nil>
======Commit i:60000, <nil>
======Commit i:70000, <nil>
======Commit i:80000, <nil>
======Commit i:90000, <nil>
======Commit i:100000, <nil>

到了这里,关于Go基于sqlx实现的sql增删改查的工具类的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Java进阶(7)——手动实现LinkedList & 内部node类的实现 & 增删改查的实现 & toString方法 & 源码的初步理解

    1.linkedList的节点,当前,上一个,下一个的思想; 2.根据index找node的方法,根据index确定从头部还是尾部; 3.linkedlist的增删改查的实现,本质是改变节点的信息; 4.递归方法实现自定义链表的toString方法; Java进阶(3)——手动实现ArrayList 源码的初步理解分析 数组插入数据和

    2024年02月11日
    浏览(36)
  • Go 语言之 SQLX 高级操作 sqlx.In

    sqlx is a package for Go which provides a set of extensions on top of the excellent built-in database/sql package. Illustrated guide to SQLX:http://jmoiron.github.io/sqlx/ sqlx:https://github.com/jmoiron/sqlx Because database/sql does not inspect your query and it passes your arguments directly to the driver, it makes dealing with queries with IN clauses

    2024年02月08日
    浏览(28)
  • 关于eclipse导入部署具有增删改查的项目

    目录 前言:当我们刚刚进入公司的第一步就是去部署当前公司的项目,本博客就是详细介绍怎么去部署当前公司的项目。 一,开发工具: 二,具体步骤: 2.1导入公司的项目 打开eclipse开发工具 2.2配置当前的环境 1导入后报错,点击buildpath 2这里我们配置修改Tomcat,jre改成与

    2024年02月13日
    浏览(33)
  • GO框架基础 (二)、sqlx库

    在 Go 语言中, sqlx 包是一个用于数据库操作的库,它建立在标准库的 database/sql 包之上,并提供了一些额外的功能,以简化和增强与数据库的交互。 sqlx 的目标是通过提供更方便的 API 和一些附加功能来改善在 Go 中进行 SQL 数据库查询的体验。 以下是 sqlx 包的一些主要特性:

    2024年02月21日
    浏览(69)
  • Go 语言之 sqlx 库使用

    sqlx is a library which provides a set of extensions on go\\\'s standard database/sql library. The sqlx versions of sql.DB , sql.TX , sql.Stmt , et al. all leave the underlying interfaces untouched, so that their interfaces are a superset on the standard ones. This makes it relatively painless to integrate existing codebases using database/sql with sqlx. Sqlx 是

    2024年02月08日
    浏览(27)
  • asp.net core 6.0 efcore +sqlserver增删改查的demo

    下面是一个使用ASP.NET Core 5.0和Entity Framework Core进行增删改查操作的示例。 首先,创建一个空的ASP.NET Core 6.0 Web应用程序项目。 然后,安装以下NuGet包: Microsoft.EntityFrameworkCore.SqlServer Microsoft.EntityFrameworkCore.Tools 接下来,创建一个数据库上下文类,用于定义实体类和数据库连接

    2024年02月13日
    浏览(33)
  • 创建nodejs项目并接入mysql,完成用户相关的增删改查的详细操作

    本文为博主原创,转载请注明出处: 在本地创建项目的文件夹名称,如 node_test,并在该文件夹下进行黑窗口执行初始化命令              Express是一个流行的Web应用程序框架,可以帮助我们快速构建Web应用程序和API。Express提供了许多有用的功能,包括路由、中间件、请求响

    2024年02月06日
    浏览(84)
  • python:使用Flask-SQLAlchemy对数据库增删改查的简单示例

    以下将介绍Flask-SQLAlchemy对数据库增删改查的简单示例。 一、安装所需的库 pip install flask flask-sqlalchemy flask-mysql 二、创建数据表 本示例使用mysql创建数据库和表 CREATE TABLE `user` (   `id` int(11) NOT NULL AUTO_INCREMENT,   `name` varchar(255) DEFAULT NULL,   `age` int(11) DEFAULT NULL,   PRIMARY KEY (`id

    2024年02月07日
    浏览(51)
  • ElasticSearch6.x版本概念介绍以及在Kibana上增删改查的操作

    教学讲解视频地址:视频地址 1.接近实时(NRT Near Real Time ) Elasticsearch是一个 接近实时 的搜索平台。这意味着, 从索引一个文档直到这个文档能够被搜索到有一个轻微的延迟(通常是1秒内) 2.索引(index) 一个索引就是一个拥有几分相似特征的文档的集合 。比如说,你可以有一个

    2023年04月24日
    浏览(38)
  • 组件分享之后端组件——基于Golang实现的全局的、版本化的、点对点的文件系统go-ipfs...

    近期正在探索前端、后端、系统端各类常用组件与工具,对其一些常见的组件进行再次整理一下,形成标准化组件专题,后续该专题将包含各类语言中的一些常用组件。欢迎大家进行持续关注。 组件: go-ipfs 开源协议:The go-ipfs project is dual-licensed under Apache 2.0 and MIT terms: Ap

    2024年02月01日
    浏览(32)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包