Table of Contents
What is MySQL
MySQL driver in Go language
Establishing a connection
Query data
Insert data
Home Database Mysql Tutorial How golang operates mysql data

How golang operates mysql data

May 27, 2023 pm 03:47 PM
mysql golang

What is MySQL

MySQL, sponsored and developed by Oracle, is a relational database management system widely used in Internet infrastructure. It supports multiple operating systems and programming languages, including the Go language, and has a series of features that support large data integration and high-performance queries.

MySQL uses a table-based data structure, with each row representing a record and each column representing a field. It uses SQL language to operate on data, the most common SQL operations include SELECT, INSERT, UPDATE, DELETE and CREATE TABLE.

MySQL driver in Go language

In Go language, we can use third-party MySQL driver to connect and query MySQL database. However, the GO language standard library already contains the database/sql package. This package has implemented the standard SQL database interface and can interact with other convenient and popular SQL databases, including MySQL, PostgreSQL and SQLite. wait.

So, before we start building a Go application that queries MySQL, we need to install the MySql driver. You can use the command line command go get -u github.com/go-sql-driver/mysql for quick installation.

This is because in the Go language, all data access must be done through the SQL.DB connection. And the purpose of the driver is to implement the interface conventions in the functions of database/sql.

Establishing a connection

In the Go language, establishing a connection to the MySQL database is based on the connection string. The connection string contains all the parameters required to connect to MySQL. Such as user name, password, host name or IP address, port number and database name, etc.

db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/dbname")
if err != nil {
    log.Fatal(err)
}
Copy after login

Query data

In Go language, you can use db.Query(), db.QueryRow()anddb.Exec() function queries and operates data in the MySQL database.

db.Query() The function is used to query multiple records and returns a *sql.Rows object. db.QueryRow() The function is used to query a single record and returns a *sql.Row object, similar to resultset, but it only returns the first row of records , usually used to query a single unique record. db.Exec() The function is used to execute non-query SQL statements, such as INSERT, UPDATE, and DELETE, returning a sql.Result object.

In this example, we use the db.Query() function to query all records. We will use a simple counter to count the number of records and print each line of data to the console.

rows, err := db.Query("SELECT id, name FROM users")
if err != nil {
    log.Fatal(err)
}
defer rows.Close()

count := 0
for rows.Next() {
    var id int
    var name string
    if err := rows.Scan(&id, &name); err != nil {
        log.Fatal(err)
    }
    fmt.Printf("id=%d, name=%s\n", id, name)
    count++
}
if err := rows.Err(); err != nil {
    log.Fatal(err)
}

fmt.Printf("Found %d users\n", count)
Copy after login

The rows.Close() function must be called after retrieving data to release the database resources associated with *sql.Rows. At the same time, the rows.Next() function is used in the code, which returns a Boolean value indicating whether there are more rows that can be processed. In addition, the rows.Scan() function is used in this example to copy the value of each row record into the id and name variables defined in this example. , and then prints each value in the console.

Insert data

We can also use Go language to insert data into the MySQL database. The simplest way is to use the db.Exec() function . We can pass the insert statement into the db.Exec() function and it will be executed in MySQL as a SQL statement.

result, err := db.Exec("INSERT INTO users(name, email) VALUES('John Doe', 'johndoe@gmail.com')")
if err != nil {
    log.Fatal(err)
}

rowsAffected, err := result.RowsAffected()
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Inserted %d rows into users table\n", rowsAffected)
Copy after login

We can use result.RowsAffected() to get the number of affected rows in the result set and use this value to print the number of updated data in the console.

The above is the detailed content of How golang operates mysql data. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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)

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

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.

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.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

Solution to MySQL encounters 'Access denied for user' problem Solution to MySQL encounters 'Access denied for user' problem Apr 11, 2025 pm 05:36 PM

How to solve the MySQL "Access denied for user" error: 1. Check the user's permission to connect to the database; 2. Reset the password; 3. Allow remote connections; 4. Refresh permissions; 5. Check the database server configuration (bind-address, skip-grant-tables); 6. Check the firewall rules; 7. Restart the MySQL service. Tip: Make changes after backing up the database.

phpmyadmin connection mysql phpmyadmin connection mysql Apr 10, 2025 pm 10:57 PM

How to connect to MySQL using phpMyAdmin? The URL to access phpMyAdmin is usually http://localhost/phpmyadmin or http://[your server IP address]/phpmyadmin. Enter your MySQL username and password. Select the database you want to connect to. Click the "Connection" button to establish a connection.

C   and Golang: When Performance is Crucial C and Golang: When Performance is Crucial Apr 13, 2025 am 12:11 AM

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

See all articles