Home  >  Article  >  Backend Development  >  What database is equipped with go language?

What database is equipped with go language?

青灯夜游
青灯夜游Original
2022-12-15 18:41:136966browse

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

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
}

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("插入成功")
}

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)
    }
}

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)
}

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("删除成功")
}

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 会在数据库中产生一条数据
}

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() //关闭
}

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

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() //关闭

}

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:
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