Home>Article>Backend Development> Can go language write database?
Go language can write databases. The difference between Go language and other languages is that Go officially does not provide a database driver, but writes a standard interface for developing database drivers. Developers can develop corresponding database drivers based on the defined interfaces; the advantage of this is that as long as it is Code developed according to standard interfaces does not require any modifications when migrating the database in the future, which greatly facilitates later architecture adjustments.
The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.
A database is a warehouse that organizes, stores and manages data according to a data structure. Compared with other storage methods, storage is only one of the functions of the database, and data organization and management are the core of the database.
Compared with databases, the disadvantages of saving data in files are:
The level of database usage is an important indicator of a programmer's ability.
MySQL is a relational database management system developed by the Swedish MySQL AB company and currently belongs to Oracle. )Its products. MySQL is one of the most popular relational database management systems, and in terms of Web applications, MySQL is one of the best RDBMS (Relational Database Management System) application software.
> mysql -h主机地址 -u用户名 -p用户密码
> mysql -h192.168.1.1 -uroot -proot
mysql> exit/quit;
func Register(name string, driver driver.Driver)Register registers and names a database, which can be used in the Open function to enable the driver. If Register registers the same name twice, or the driver parameter is nil, panic will occur.
func init() { sql.Register("mysql", &MySQLDriver{}) }The package will automatically call the init function in the package during the introduction process. Therefore, when registering the database driver, you only need to use anonymous import to reference the package, so that the code can directly use this database driver. .
import ( "database/sql" _ "github.com/go-sql-driver/mysql" )
.
3.1 Connecting to the database
In the Go language, the sql package provides an Open method to create a database connection.func Open(driverName, dataSourceName string) (*DB, error)Open opens a database specified by dirverName, and dataSourceName specifies the data source, which generally includes at least the database file name and (possible) connection information. The Open function only verifies its parameters and does not create a connection to the database. If you want to check whether the name of the data source is legal, you should call the Ping method that returns a value.
func (db *DB) Ping() errorPing checks whether the connection to the database is still valid and creates a connection if necessary.
package main import ( "database/sql" _ "github.com/go-sql-driver/mysql" "log" ) func main() { db, err := sql.Open("mysql", "root:200039@tcp(127.0.0.1:3306)/gostudy") if err != nil { log.Fatal(err) } defer db.Close() //验证连接的可用性 err = db.Ping() if err != nil { log.Fatal("数据库连接失败:", err) } log.Println("数据库连接成功!") }Creating a MySQL data table requires definitions Table name, table field names, field types and constraints. The syntax structure of creating a data table is:
CREATE TABLE 表名 ( 字段名1 数据类型 [列级别约束条件] [默认值], 字段名2 数据类型 [列级别约束条件] [默认值], 字段名3 数据类型 [列级别约束条件] [默认值], ... [表级别约束条件] );Create a data table
CREATE TABLE `user`( `uid` INT(10) NOT NULL AUTO_INCREMENT, `username` VARCHAR(64) NULL DEFAULT 1, `gender` TINYINT(1) NULL DEFAULT NULL, `password` VARCHAR(64) NULL DEFAULT NULL, `created` DATE NULL DEFAULT NULL, PRIMARY KEY (`uid`) );
使用Go语言创建数据表需要使用Exec函数。
func (db *DB) Exec(query string, args ...interface{}) (Result, error)
Exec执行一次命令(包括查询、删除、更新、插入等),不返回任何执行结果。参数args表示query中的占位参数。
Exec的返回值为Result接口,Result的定义如下:
type Result interface { LastInsertId() (int64, error) RowsAffected() (int64, error) }
Result主要有两个方法。LastInsertId返回一个数据库生成的回应命令的整数,当插入新行时,返回由数据库执行插入操作得到的自增ID号。RowsAffected返回被update、insert或delete命令影响的行数。
MySQL中使用INSERT INTO语句来插入数据,插入的语法结构为:
INSERT INTO table_name ( field1, field2,...fieldN ) VALUES ( value1, value2,...valueN );
如果需要同时插入多条数据,可以使用如下方式:
INSERT INTO table_name (field1, field2,...fieldN) VALUES (valueA1,valueA2,...valueAN),(valueB1,valueB2,...value BN)......;
package main import ( "database/sql" _ "github.com/go-sql-driver/mysql" "log" "time" ) func checkErr(err error) { if err != nil { log.Fatal(err) } } func main() { db, err := sql.Open("mysql", "root:200039@tcp(127.0.0.1:3306)/gostudy") checkErr(err) defer db.Close() //验证连接可用性 err = db.Ping() checkErr(err) log.Println("数据库连接成功") rs, err := db.Exec("insert into `user`(username,gender,password,created) values (?,?,?,?)", "tom", 1, "123456", time.Now()) checkErr(err) rowCount, err := rs.RowsAffected() checkErr(err) log.Printf("插入了 % d行", rowCount) }
SQL注入(SQLi)是一种注入攻击,可以执行恶意SQL语句。它通过将任意SQL代码插入数据库查询,使攻击者能够完全控制Web应用程序后面的数据库服务器。攻击者可以使用SQL注入漏洞绕过应用程序安全措施;可以绕过网页或Web应用程序的身份验证和授权,并检索整个SQL数据库的内容;还可以使用SQL注入来添加、修改和删除数据库中的记录。
sql包还提供一种预编译的方式来执行SQL语句,通常在处理批量SQL语句时会用到这种方式,这种方式比手动拼接字符串SQL语句高效,还可以防止SQL注入攻击。
func (db *DB) Prepare(query string) (*Stmt, error)
Prepare创建一个准备好的状态用于之后的查询和命令。返回值可以同时执行多个查询和命令。
package main import ( "database/sql" _ "github.com/go-sql-driver/mysql" "log" "time" ) func checkErr(err error) { if err != nil { log.Fatal(err) } } func main() { db, err := sql.Open("mysql", "root:200039@tcp(127.0.0.1:3306)/gostudy") checkErr(err) defer db.Close() //验证连接可用性 err = db.Ping() checkErr(err) log.Println("数据库连接成功") //rs, err := db.Exec("insert into `user`(username,gender,password,created) values (?,?,?,?)", "tom", 1, "123456", time.Now()) stmt, err := db.Prepare("INSERT INTO `user`(username,gender,password,created) VALUES (?,?,?,?)") defer stmt.Close() rs, err := stmt.Exec("Ailsa", 0, "111111", time.Now()) checkErr(err) rowCount, err := rs.RowsAffected() checkErr(err) log.Printf("插入了 % d行", rowCount) }
MySQL数据库使用SELECT语句来查询数据。以下为在MySQL数据库中查询数据通用的SELECT语法:
SELECT column_name,column_name FROM <表 1>, <表 2>... JOIN<表3>on... [WHERE <表达式> [GROUP BY[HAVING [{ }...]] [ORDER BY ] [LIMIT[ ,] ]
语法解释:
在Go语言中,我们可以使用Query函数来查询数据:
func (db *DB) Query(query string, args ...interface{}) (*Rows, error)
Query执行一次查询,返回多行结果(即Rows),一般用于执行SELECT命令。参数args表示
Query中的占位参数,Rows是查询的结果。它的游标指向结果集的第0行,使用Next方法来遍历各行结果。查询到数据后使用rows.Next获取一行结果,并使用Scan将查询到的结果赋值到目标变量中。
func (r *Row) Scan(dest ...interface{}) error
package main import ( "database/sql" _ "github.com/go-sql-driver/mysql" "log" ) type User struct { Uid int Username string Gender bool Password string Created string } func checkErr(err error) { if err != nil { log.Fatal(err) } } func main() { db, err := sql.Open("mysql", "root:200039@tcp(127.0.0.1:3306)/gostudy") checkErr(err) defer db.Close() //验证连接的可用性 err = db.Ping() checkErr(err) log.Println("数据库连接成功!") rows, err := db.Query("select * from `user` where username=?", "Tom") defer rows.Close() for rows.Next() { user := User{} err := rows.Scan(&user.Uid, &user.Username, &user.Gender, &user.Password, &user.Created) checkErr(err) log.Println(user) } }
如果需要修改或更新MySQL中的数据,我们可以使用UPDATE命令来操作。
UPDATE <表名> SET 字段 1=值 1 [,字段 2=值 2... ] [WHERE 子句 ] [ORDER BY 子句] [LIMIT 子句]
语法解释:
注意:修改一行数据的多个列值时,SET子句的每个值用逗号分开即可。
rs, err := db.Exec("update `user` set password=? where sername=?","123123","john") checkErr(err) rowCount, err := rs.RowsAffected() checkErr(err) if rowCount > 0 { log.Println("更新成功!") }
MySQL使用DELETE语句从单个表中删除数据,语法格式为:
DELETE FROM <表名> [WHERE 子句] [ORDER BY 子句] [LIMIT 子句]
语法解释:
注意:在不使用WHERE条件的时候,将删除所有数据;数据库一旦删除数据,数据就会永远
消失。因此,在执行DELETE语句之前,应该先备份数据库,以防需要找回被删除的数据。
rs, err := db.Exec("delete from `user` where uid=?",3) checkErr(err) rowCount, err := rs.RowsAffected() checkErr(err) if rowCount > 0 { log.Println("删除成功!") }
MySQL数据库中的事务是用户一系列的数据库操作序列,这些操作要么全做,要么全不做,是一个不可分割的工作单位。
事务具有四个特性:原子性(Atomicity)、一致性(Consistency)、隔离性(Isolation)和持久性(Durability)。这四个特性简称为ACID原则。
原子性
事务必须是原子工作单元,事务中的操作要么全部执行,要么全都不执行,不能只完成部分操作。原子性在数据库系统中由恢复机制来实现。
一致性
事务开始之前,数据库处于一致性的状态;事务结束后,数据库必须仍处于一致性状态。数
据库一致性的定义是由用户负责的。例如,在银行转账中,用户可以定义转账前后两个账户金额之和保持不变。
隔离性
系统必须保证事务不受其他并发执行事务的影响,即当多个事务同时运行时,各事务之间相
互隔离,不可互相干扰。事务查看数据时数据所处的状态,要么是另一个并发事务修改它之前的状态,要么是另一个并发事务修改它之后的状态,事务不会查看中间状态的数据。隔离性通过系统的并发控制机制实现。
持久性
一个已完成的事务对数据所做的任何变动在系统中是永久有效的,即使该事务产生的修改不
正确,错误也将一直保持。持久性通过恢复机制实现,发生故障时,可以通过日志等手段恢复数据库信息。
事务的ACID原则保证了一个事务或者成功提交,或者失败回滚,二者必居其一。因此,它对事务的修改具有可恢复性,即当事务失败时,它对数据的修改都会恢复到该事务执行前的状态。
简单来说,事务处理就两个过程,要么成功提交,要么失败回滚,在Go语言中使用Tx结构体来表示事务。
type Tx interface{ Commit() error Rollback() error }
Tx代表一个进行中的数据库事务。一次事务必须以对Commit或Rollback的调用结束。调用Commit或Rollback后,所有对事务的操作都会失败并返回错误值ErrTxDone。
package main import ( "database/sql" _ "github.com/go-sql-driver/mysql" "log" ) func checkErr(err error) { if err != nil { log.Fatal(err) } } func checkErrWithTx(err error, tx *sql.Tx) { if err != nil { tx.Rollback() log.Fatal(err) } } func main() { db, err := sql.Open("mysql", "root:200039@tcp(127.0.0.1:3306)/gostudy") checkErr(err) defer db.Close() //验证连接的可用性 err = db.Ping() checkErr(err) log.Println("数据库连接成功!") var password string tx, err := db.Begin() checkErr(err) //查找Tom的密码,如果密码为123456就将密码改为111111,否则不执行任何操作 err = tx.QueryRow("select password from `user` where username=?", "Tom").Scan(&password) checkErrWithTx(err, tx) if password == "123456" { rs, err := tx.Exec("update `user` set password=? where username=?", "111111", "Tom") checkErrWithTx(err, tx) rowCount, err := rs.RowsAffected() checkErrWithTx(err, tx) if rowCount > 0 { log.Println("密码更新完成!") } } tx.Commit() log.Println("事务处理完成!") }
数据库(Database)
所谓“数据库”,是以一定方式存储在一起、能与多个用户共享、具有尽可能小的冗余度、
与应用程序彼此独立的数据集合。MySQL中使用的数据库是关系型数据库(Relational Database)。一个数据库由一个或一组数据表组成。每个数据库都以文件的形式存放在磁盘上,即对应于一个物理文件。不同的数据库与物理文件对应的方式也不一样。
数据表(Table)
数据表简称表,由一组数据记录组成,数据库中的数据是以表为单位进行组织的。一个表是
一组相关的按行排列的数据,每个表中都含有相同类型的信息。表实际上是一个二维表格,例如一个班所有学生的考试成绩可以存放在一个表中,表中的每一行对应一个学生,这一行包括学生的学号、姓名及各门课程成绩。
记录(Record)
表中的每一行称为一个记录,它由若干个字段组成。
字段(Field)
字段也称域。表中的每一列称为一个字段。每个字段都有相应的描述信息,如数据类型、数
据宽度等。
索引(Index)
In order to improve the efficiency of accessing the database, you can use indexes on the database. When searching for a specified record
in a larger database, there is a big difference in efficiency between using an index and not using an index. An index is actually a special type of table that contains the values of key fields (defined by the user) and pointers to the actual record locations. These values and pointers are stored in a specific order (also defined by the user) so that they can be stored in a specific order (also defined by the user). Find the required data records faster.
Query
Query is a SQL (Structured Query Language) command used to obtain a specified set of records from one or more tables. Or
Perform specified operations on a table. When reading data from the database, we often hope that the read data meets certain conditions and can be sorted by a certain field. Using SQL can make this operation easier and more efficient. SQL is a non-procedural language (some people call it a fourth-generation language). When using it to find a specified record, you only need to indicate what to do, not how to do it. Each statement can be regarded as a query. According to this query, the required query results can be obtained.
Filter (Filter)
Filter is a component of the database. It combines indexing and sorting to set conditions, and then based on the given
conditional output required data.
View (View)
The view of the data refers to the number of records found (or processed) and the order in which these records are displayed (or processed). In general, it is actually a two-dimensional table. For example, the test scores of all students in a class can be stored in a table. Each row in the table corresponds to a student. This row includes the student's student number, name and subject. Course results.
Go video tutorial,Programming teaching】
The above is the detailed content of Can go language write database?. For more information, please follow other related articles on the PHP Chinese website!