You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: eBook/05.5.md
+63-66
Original file line number
Diff line number
Diff line change
@@ -2,12 +2,11 @@
2
2
3
3
( ***Project beedb is no longer maintained, but code still there*** )
4
4
5
-
beedb is a ORM, "Object/Relational Mapping", that developed in Go by me.
6
-
It uses Go style to operate database, implemented mapping struct to database records. It's a lightweight Go ORM framework, the purpose of developing this ORM is to help people learn how to write ORM, and finds a good balance between functions and performance.
5
+
beedb es un ORM, "Object / Relational Mapping", que se desarrolló en Go por mí. Utiliza Go estilo para operar la base de datos, estructura de asignación aplicado a los registros de base de datos. Es un marco Go ORM ligero, con el propósito de desarrollar este ORM es ayudar a las personas a aprender cómo escribir ORM, y encuentra un buen equilibrio entre las funciones y el rendimiento.
7
6
8
-
beedb is an open source project, and supports basic functions of ORM, but doesn't support associated query.
7
+
beedb es un proyecto de código abierto, y es compatible con las funciones básicas de la ORM, pero no admite la consulta asociada.
9
8
10
-
Because beedb support`database/sql`interface standards, so any driver that supports this interface can be used in beedb, I've tested following drivers:
9
+
Debido a que beedb soporta`database/sql`interfaz estándar, cualquier controlador compatible con esta interfaz se pueden utilizar en beedb, he probado los siguientes controladores:
`beedb.New()`actually has two arguments, the first one is for standard requirement, and the second one is for indicating database engine, but if you are using MySQL/SQLite, you can just skip the second one.
47
+
`beedb.New()`en realidad tiene dos argumentos, el primero es para el requisito estándar, y el segundo es para indicar el motor de base de datos, pero si usted está utilizando MySQL / SQLite, puede saltarse la segunda.
49
48
50
-
Otherwise, you have to initialize, like SQLServer:
49
+
De lo contrario, usted tiene que inicializar, como SQLServer:
51
50
52
51
orm = beedb.New(db, "mssql")
53
52
54
53
PostgreSQL:
55
54
56
55
orm = beedb.New(db, "pg")
57
56
58
-
beedb supports debug, and use following code to enable:
57
+
beedb soporta depuración, use el siguiente código para permitirlo:
59
58
60
59
beedb.OnDebug=true
61
60
62
-
Now we have a struct for the database table `Userinfo`that we used in previous sections.
61
+
Ahora tenemos una estructura para la base de datos de la tabla `Userinfo`que hemos utilizado en las secciones anteriores.
63
62
64
63
type Userinfo struct {
65
-
Uid int `PK` // if the primary key is not id, you need to add tag `PK` for your customized primary key.
64
+
Uid int `PK` // si la clave principal no es id, es necesario agregar `tag` PK para su clave primaria personalizada.
66
65
Username string
67
66
Departname string
68
67
Created time.Time
69
68
}
70
69
71
-
Be aware that beedb auto-convert your camel style name to underline and lower case letter. For example, we have `UserInfo` as the struct name, and it will be `user_info` in database, same rule for field name.
72
-
Camel
70
+
Tenga en cuenta que beedb auto-convert su estilo a para subrayar y letra minúscula. Por ejemplo, tenemos `UserInfo` como el nombre struct, y será `user_info` en la base de datos, la misma regla para el nombre del campo
73
71
74
-
## Insert data
72
+
## Isertar datos
75
73
76
-
The following example shows you how to use beedb to save a struct instead of SQL command, and use Save method to apply change.
74
+
El siguiente ejemplo muestra cómo utilizar beedb para salvar una estructura en lugar de comandos SQL y utilizar Guardar método para aplicar el cambio.
77
75
78
76
var saveone Userinfo
79
77
saveone.Username = "Test Add User"
80
78
saveone.Departname = "Test Add Departname"
81
79
saveone.Created = time.Now()
82
80
orm.Save(&saveone)
83
81
84
-
And you can check`saveone.Uid`after inserted, its value is self-increase ID, Save method did this job for you.
82
+
Y se puede comprobar`saveone.Uid`después insertado, su valor es self-increase ID, método Save hizo este trabajo para usted.
85
83
86
-
beedb provides another way to insert data, which is using map.
84
+
beedb proporciona otra forma de insertar los datos, que está utilizando map.
87
85
88
86
add := make(map[string]interface{})
89
87
add["username"] = "astaxie"
90
88
add["departname"] = "cloud develop"
91
89
add["created"] = "2012-12-02"
92
90
orm.SetTable("userinfo").Insert(add)
93
91
94
-
Insert multiple data:
92
+
Insertar datos múltiples:
95
93
96
94
addslice := make([]map[string]interface{}, 10)
97
95
add:=make(map[string]interface{})
@@ -105,36 +103,36 @@ Insert multiple data:
105
103
addslice =append(addslice, add, add2)
106
104
orm.SetTable("userinfo").InsertBatch(addslice)
107
105
108
-
The way I showed you above is like chain query, you should be familiar if you know jquery. It returns original ORM object after calls, and continue to do other jobs.
106
+
La forma en que te mostré arriba es como una consulta, Ud., debe estar familiarizado si sabe jQuery. Devuelve objeto ORM original después de las llamadas y sigue haciendo otros trabajos.
109
107
110
-
The method`SetTable`tells ORM we want to insert our data to table`userinfo`.
108
+
El metodo`SetTable`dice ORM queremos insertar los datos de la tabla`userinfo`.
111
109
112
-
## Update data
110
+
## Actualización de datos
113
111
114
-
Continue above example to show how to update data. Now we have primary key value of saveone(Uid), so beedb executes update operation instead of inserting new record.
112
+
Siga el ejemplo anterior para mostrar cómo actualizar datos. Ahora tenemos el valor de clave principal de saveone (UID), por lo que beedb ejecuta operación de actualización en lugar de insertar nuevo registro.
115
113
116
114
saveone.Username = "Update Username"
117
115
saveone.Departname = "Update Departname"
118
116
saveone.Created = time.Now()
119
117
orm.Save(&saveone) // update
120
118
121
-
You can use map for updating data also:
119
+
Usted puede utilizar map para la actualización de datos también:
Voy a explicar algunos de los métodos que hemos utilizado anteriormente:
128
126
129
-
-`.SetPK()`tells ORM `uid`is the primary key of table`userinfo`.
130
-
-`.Where()`sets conditions, supports multiple arguments, if the first argument is a integer, it's a short form of`Where("<primary key>=?", <value>)`.
131
-
-`.Update()`method accepts map and update to database.
127
+
-`.SetPK()`le dice a ORM `uid`es la clave principal de la tabla`userinfo`.
128
+
-`.Where()`establece las condiciones, soporta múltiples argumentos, si el primer argumento es un número entero, es una forma corta de dónde`Where("<primary key>=?", <value>)`.
129
+
-`.Update()`método que acepta map y actualización de base de datos.
132
130
133
-
## Query data
131
+
## Datos de la consulta
134
132
135
-
beedb query interface is very flexible, let's see some examples:
133
+
interfaz de consulta beedb es muy flexible, veamos algunos ejemplos:
136
134
137
-
Example 1, query by primary key:
135
+
Ejemplo 1, consulta por clave principal:
138
136
139
137
var user Userinfo
140
138
// Where accepts two arguments, supports integers
@@ -145,94 +143,93 @@ Example 2:
145
143
var user2 Userinfo
146
144
orm.Where(3).Find(&user2) // short form that omits primary key
147
145
148
-
Example 3, other query conditions:
146
+
Ejemplo 3, otras condiciones de la consulta:
149
147
150
148
var user3 Userinfo
151
149
// Where accepts two arguments, supports char type.
152
150
orm.Where("name = ?", "john").Find(&user3)
153
151
154
-
Example 4, more complex conditions:
152
+
Ejemplo 4, las condiciones más complejas:
155
153
156
154
var user4 Userinfo
157
155
// Where accepts three arguments
158
156
orm.Where("name = ? and age < ?", "john", 88).Find(&user4)
159
157
160
-
Examples to get multiple records:
158
+
Ejemplos de conseguir varios registros:
161
159
162
-
Example 1, gets 10 records that `id>3` and starts with position 20:
160
+
Ejemplo 1, recibe 10 registros que id> 3 y se inicia con la posición 20:
As you can see, the Limit method is for limiting number of results.
175
+
Como puede ver, el método de límite es para limitar el número de resultados.
178
176
179
-
-`.Limit()`supports two arguments, which are number of results and start position. 0 is the default value of start position.
180
-
-`.OrderBy()`is for ordering results, the arguments is the order condition.
177
+
-`.Limit()`admite dos argumentos, que son el número de resultados y la posición de inicio. 0 es el valor predeterminado de la posición de inicio.
178
+
-`.OrderBy()`es para ordenar los resultados, que los argumentos es la condición de la orden.
181
179
182
-
All examples that you see is mapping records to structs, and you can also just put data into map as follows:
180
+
Todos los ejemplos que se ven son registros cartográficos a las estructuras, y también se puede simplemente poner los datos en el map de la siguiente manera:
183
181
184
182
a, _ := orm.SetTable("userinfo").SetPK("uid").Where(2).Select("uid,username").FindMap()
185
183
186
-
-`.Select()`tells beedb how many fields you want to get from database table, returns all fields as default.
187
-
-`.FindMap()`returns type `[]map[string][]byte`, so you need to convert to other types by yourself.
184
+
-`.Select()`le dice a beedb cuántos campos que desea obtener de la tabla de base de datos, devuelve todos los campos por defecto.
185
+
-`.FindMap()` devuelve el tipo `[]map[string][]byte`, si necesita para convertir a otros tipos.
188
186
189
-
## Delete data
187
+
## Eliminar los datos
190
188
191
-
beedb provides rich methods to delete data.
189
+
beedb proporciona muchos métodos para eliminar datos.
192
190
193
-
Example 1, delete a single record:
191
+
Ejemplo 1, eliminar un solo registro:
194
192
195
193
// saveone is the one in above example.
196
194
orm.Delete(&saveone)
197
195
198
-
Example 2, delete multiple records:
196
+
Ejemplo 2, eliminar varios registros:
199
197
200
198
// alluser is the slice which gets multiple records.
Copy file name to clipboardExpand all lines: eBook/05.6.md
+10-11
Original file line number
Diff line number
Diff line change
@@ -1,25 +1,25 @@
1
1
# 5.6 NoSQL database
2
2
3
-
A NoSQL database provides a mechanism for storage and retrieval of data that use looser consistency models than relational database in order to achieve horizontal scaling and higher availability. Some authors refer to them as "Not only SQL" to emphasize that some NoSQL systems do allow SQL-like query language to be used.
3
+
Una base de datos NoSQL proporciona un mecanismo para el almacenamiento y recuperación de datos que utilizan los modelos de consistencia más flojas que base de datos relacional para lograr la escala horizontal y una mayor disponibilidad. Algunos autores se refieren a ellos como "No sólo SQL" para enfatizar que algunos sistemas NoSQL permiten que el lenguaje de consulta similar a SQL que se utilizará.
4
4
5
-
As the C language of 21st century, Go has good support for NoSQL databases, and the popular NoSQL database including redis, mongoDB, Cassandra and Membase.
5
+
Como el lenguaje C de siglo 21, Go tiene un buen soporte para bases de datos NoSQL, y la base de datos NoSQL populares incluyendo redis, mongoDB, Cassandra and Membase.
6
6
7
7
## redis
8
8
9
-
redis is a key-value storage system like Memcached, it supports string, list, set and zset(ordered set) as it's value types.
9
+
Redis es un sistema de almacenamiento de conkey-value como Memcached, es compatible con string, list, set and zset(ordered set) ya que evalua tipos.
Let's see how to use the driver that I forked to operate database:
22
+
Vamos a ver cómo utilizar el controlador que bifurqué para operar la base de datos:
23
23
24
24
package main
25
25
@@ -52,17 +52,17 @@ Let's see how to use the driver that I forked to operate database:
52
52
client.Del("l")
53
53
}
54
54
55
-
We can see that it's quite easy to operate redis in Go, and it has high performance. Its client commands are almost the same as redis built-in commands.
55
+
Podemos ver que es muy fácil de operar redistribución en Go, y tiene un alto rendimiento. Sus comandos de cliente son casi los mismos que redis incorporados comandos.
56
56
57
57
## mongoDB
58
58
59
-
mongoDB (from "humongous") is an open source document-oriented database system developed and supported by 10gen. It is part of the NoSQL family of database systems. Instead of storing data in tables as is done in a "classical" relational database, MongoDB stores structured data as JSON-like documents with dynamic schemas (MongoDB calls the format BSON), making the integration of data in certain types of applications easier and faster.
59
+
mongoDB (de "descomunal") es un sistema de base de datos orientada a documentos de código abierto desarrollado y apoyado por 10gen. Es parte de la familia de los sistemas de base de datos NoSQL. En lugar de almacenar datos en tablas como se hace en una base de datos relacional "clásica", tiendas de MongoDB datos estructurados como documentos JSON-como con esquemas dinámicos (MongoDB llama al BSON formato), por lo que la integración de datos en ciertos tipos de aplicaciones más fácil y más rápido .
60
60
61
61

62
62
63
63
Figure 5.1 MongoDB compares to Mysql
64
64
65
-
The best driver for mongoDB is called `mgo`, and it is possible to be in the standard library in the future.
65
+
El mejor controlador para mongoDB se llama `mgo`, y es posible que este en la librería estándar en el futuro.
66
66
67
67
Here is the example:
68
68
@@ -104,8 +104,7 @@ Here is the example:
104
104
fmt.Println("Phone:", result.Phone)
105
105
}
106
106
107
-
We can see that there is no big different to operate database between mgo and beedb, they are both based on struct, this is what Go style is.
108
-
107
+
Podemos ver que no hay un diferente grande para operar la base de datos entre MgO y beedb, ambos están basados en estructura, esto es lo que Go estilo es.
In this chapter, you first learned the design of `database/sql`interface, and many third-party database drivers for different kinds of database. Then I introduced beedb to you, an ORM for relational databases, also showed some samples for operating database. In the end, I talked about some NoSQL databases, I have to see Go gives very good support for those NoSQL databases.
3
+
En este capítulo, primero aprendió el diseño de `database/sql`interfaz, y muchos conductores de bases de datos de terceros para diferentes tipos de base de datos. Entonces me presenté beedb a usted, un ORM para bases de datos relacionales, también mostró algunas muestras para la base de datos de funcionamiento. Al final, he hablado de algunas bases de datos NoSQL, tengo que ver a Go da muy buen soporte para las bases de datos NoSQL.
4
4
5
-
After read this chapter, I hope you know how to operate databases in Go. This is the most important part in web development, so I want to you completely understand design ideas of `database/sql`interface.
5
+
Después de leer este capítulo, espero que sepas cómo operar bases de datos en Go. Esta es la parte más importante en el desarrollo web, así que quiero que entienda completamente las ideas de diseño de `database/sql`interfaz.
6
6
7
7
## Links
8
8
9
9
-[Directory](preface.md)
10
10
- Previous section: [NoSQL database](05.6.md)
11
-
- Next section: [Data storage and session](06.0.md)
11
+
- Next section: [Data storage and session](06.0.md)
0 commit comments