Home Backend Development Golang What database is equipped with go language?

What database is equipped with go language?

Dec 15, 2022 pm 06:41 PM
golang database go language

What database is equipped with go language?

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.

golang supports a variety of databases

1. MySQL

MySQL is a relational database management system. MySQL adopts With the dual authorization policy, data can be saved in different tables, thereby increasing the speed and flexibility of the database. It has the characteristics of small size, fast speed, and low total cost of ownership.

2. Oracle

oracle is a relational database management system, which is in a leading position in the database field. Its leading position has the characteristics of good portability, easy use and powerful functions, and is suitable for various applications. It is a database with high efficiency, good reliability and high throughput that can be used in large, medium, small and microcomputer environments.

3. SQLite

SQLite is a lightweight database that follows the ACID relational database management system. It is designed for embedded use. SQLite can be used in many embedded products. At the same time It can be used in combination with C#, PHP, Java and other programming languages.

4. MongoDB

MongoDB is a database based on distributed file storage. Its purpose is to provide scalable and high-performance data storage solutions for WEB applications. The data structure supported by MongoDB is very loose. And supports multiple query languages ​​and indexing.

5. PostgreSQL

PostgreSQL is a powerful, open-source object-relational database management system with complex queries, foreign keys, triggers, views, transaction integrity, and multiple versions. With features such as concurrency control, PostgreSQL can execute instruction programs on the database server through functions, and users can customize index methods.

6. SQL Sever

SQL Sever is a relational database management system. It has the advantages of easy use, good scalability, and high degree of related software integration, and can provide safer and more reliable storage. Performance, use SQL Sever to build and manage highly available and high-performance data applications for business.

Golang operates MySQL database

The following mainly introduces the use of mysql in go language from the aspects of addition, deletion, query, modification and things

1. Connect to the database

Use the sql.Open() function to open the database connection. The database connection string (dsn) format is as follows:

admin:123456@tcp(10.2.1.5)/irisapp
Copy after login

The code is as follows:

func (f *mysql_db) mysql_open() {
    db, err := sql.Open("mysql", dbusername+":"+dbpassword+"@tcp("+dbhostsip+")/"+dbname)
    if err != nil {
        fmt.Println("链接失败")
    }
    fmt.Println("链接成功")
    f.db = db
}
Copy after login

2. Insert

func (f *mysql_db) mysql_insert() { //insert  添加数据
    fmt.Println("开始插入")
    stmt, err := f.db.Prepare("INSERT INTO depart(departName,memo) VALUES(?,?)")
    //defer stmt.Close()
    if err != nil {
        fmt.Println("插入失败")
        return
    }
    stmt.Exec("dd", "adadcccda")
    fmt.Println("插入成功")
}
Copy after login

3. Query

func (f *mysql_db) mysql_select(sql_data string) {   //select 查询数据
    fmt.Println("sql:", sql_data)
    rows, err := f.db.Query(sql_data)
    if err != nil {
        fmt.Println("查询失败")
    }
    for rows.Next() {
        var departID int
        var departName string
        var memo string
        err = rows.Scan(&departID, &departName, &memo)
        if err != nil {
            panic(err)
        }
        fmt.Println("departName:", departName)
    }
}
Copy after login

4. Update

func (f *mysql_db) mysql_update() { //update  修改数据
    stmt, err := f.db.Prepare("update depart set departName=?,memo =? where departId=?")
    //defer stmt.Close()
    if err != nil {
        //错误处理
    }
    result,_ := stmt.Exec("aa","asdfadsadsfa",1)
    if result == nil {
        fmt.Println("修改失败")
    }
    affect_count,_ := result.RowsAffected()    //返回影响的条数,注意有两个返回值
    fmt.Println("%v",affect_count)
}
Copy after login

5. Delete

func (f *mysql_db) mysql_delete() { //delete  删除数据
    stmt, err := f.db.Prepare("delete from depart where departId=?")
    //defer stmt.Close()
    if err != nil {
        //错误处理
    }
    stmt.Exec(2)     //不返回任何结果
    fmt.Println("删除成功")
}
Copy after login

6. Things

func (f *mysql_db) mysql_tran(){
    //事务
    tx,err := f.db.Begin()        //声明一个事务的开始
    if err != nil {
        fmt.Println(err)
        return
    }
    insert_sql := "insert into depart (departName,memo) VALUES(?,?)"
    insert_stmt,insert_err := tx.Prepare(insert_sql)
    if insert_err != nil {
        fmt.Println(insert_err)
        return
    }
    insert_res,insert_err := insert_stmt.Exec("ff","ff")
    last_insert_id,_ := insert_res.LastInsertId()
    fmt.Println(last_insert_id)
    // defer tx.Rollback()            //回滚之前上面的last_login_id是有的,但在回滚后该操作没有被提交,被回滚了,所以上面打印的Last_login_id的这条数据是不存在与数据库表中的
    tx.Commit()                        //这里提交了上面的操作,所以上面的执行的sql 会在数据库中产生一条数据
}
Copy after login

Call

func main() {
    db := &mysql_db{}
    db.mysql_open()
    db.mysql_insert()
    db.mysql_update()
    db.mysql_delete()
    db.mysql_tran()
    db.mysql_select("select departID,departName,memo from depart")
    db.mysql_close() //关闭
}
Copy after login

The output after startup is as follows:

D:\Go_Path\go\src\mysqldemo>go run mysqldemo.go
链接成功
开始插入
插入成功
0
删除成功
10
sql: select departID,departName,memo from depart
departName: aa
departName: dd
departName: dd
departName: dd
departName: dd
departName: dd
departName: ff
departName: dd
departName: ff
Copy after login

Complete code

package main

import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
    )

var (
    dbhostsip  = "10.2.1.5:3306"
    dbusername = "admin"
    dbpassword = "123456"
    dbname     = "irisapp"
)

type mysql_db struct {
    db *sql.DB
}

func (f *mysql_db) mysql_open() {
    db, err := sql.Open("mysql", dbusername+":"+dbpassword+"@tcp("+dbhostsip+")/"+dbname)
    if err != nil {
        fmt.Println("链接失败")
    }
    fmt.Println("链接成功")
    f.db = db
}

func (f *mysql_db) mysql_close() {
    defer f.db.Close()
}

func (f *mysql_db) mysql_select(sql_data string) {   //select 查询数据
    fmt.Println("sql:", sql_data)
    rows, err := f.db.Query(sql_data)
    if err != nil {
        fmt.Println("查询失败")
    }
    for rows.Next() {
        var departID int
        var departName string
        var memo string
        err = rows.Scan(&departID, &departName, &memo)
        if err != nil {
            panic(err)
        }
        fmt.Println("departName:", departName)
    }

}

func (f *mysql_db) mysql_insert() { //insert  添加数据
    fmt.Println("开始插入")
    stmt, err := f.db.Prepare("INSERT INTO depart(departName,memo) VALUES(?,?)")
    //defer stmt.Close()
    if err != nil {
        fmt.Println("插入失败")
        return
    }
    stmt.Exec("dd", "adadcccda")
    fmt.Println("插入成功")
}

func (f *mysql_db) mysql_update() { //update  修改数据
    stmt, err := f.db.Prepare("update depart set departName=?,memo =? where departId=?")
    //defer stmt.Close()
    if err != nil {
        //错误处理
    }
    result,_ := stmt.Exec("aa","asdfadsadsfa",1)
    if result == nil {
        fmt.Println("修改失败")
    }
    affect_count,_ := result.RowsAffected()    //返回影响的条数,注意有两个返回值
    fmt.Println(affect_count)
}

func (f *mysql_db) mysql_delete() { //delete  删除数据
    stmt, err := f.db.Prepare("delete from depart where departId=?")
    //defer stmt.Close()
    if err != nil {
        //错误处理
    }
    stmt.Exec(2)     //不返回任何结果
    fmt.Println("删除成功")
}

func (f *mysql_db) mysql_tran(){
    //事务
    tx,err := f.db.Begin()        //声明一个事务的开始
    if err != nil {
        fmt.Println(err)
        return
    }
    insert_sql := "insert into depart (departName,memo) VALUES(?,?)"
    insert_stmt,insert_err := tx.Prepare(insert_sql)
    if insert_err != nil {
        fmt.Println(insert_err)
        return
    }
    insert_res,insert_err := insert_stmt.Exec("ff","ff")
    last_insert_id,_ := insert_res.LastInsertId()
    fmt.Println(last_insert_id)
    // defer tx.Rollback()            //回滚之前上面的last_login_id是有的,但在回滚后该操作没有被提交,被回滚了,所以上面打印的Last_login_id的这条数据是不存在与数据库表中的
    tx.Commit()                        //这里提交了上面的操作,所以上面的执行的sql 会在数据库中产生一条数据
}

func main() {
    db := &mysql_db{}
    db.mysql_open()
    db.mysql_insert()
    db.mysql_update()
    db.mysql_delete()
    db.mysql_tran()
    db.mysql_select("select departID,departName,memo from depart")
    db.mysql_close() //关闭

}
Copy after login

Summary

1. Supports preparation expressions, which can be used Optimize SQL queries to improve performance and reduce the risk of SQL injection. Both db.Prepare() and tx.Prepare provide support for prepared expressions.

2. LastInsertId() Get the id of the first inserted item

3. RowsAffected() Get the number of affected/inserted items

4. Here is just a brief introduction to go The basic use of MySQL in Go language development in language development. In fact, in the actual development process, ORM-related third-party frameworks are mainly used, but the underlying principles still need to be learned.

For more go language knowledge, please pay attention to the go language tutorial column on the PHP Chinese website.

The above is the detailed content of What database is equipped with go language?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

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.

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

Golang's Purpose: Building Efficient and Scalable Systems Golang's Purpose: Building Efficient and Scalable Systems Apr 09, 2025 pm 05:17 PM

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

In Go programming, how to correctly manage the connection and release resources between Mysql and Redis? In Go programming, how to correctly manage the connection and release resources between Mysql and Redis? Apr 02, 2025 pm 05:03 PM

Resource management in Go programming: Mysql and Redis connect and release in learning how to correctly manage resources, especially with databases and caches...

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

See all articles