简体   繁体   English

有没有办法在 mySQL 数据库中存储对象?

[英]Is there a way to store objects in a mySQL database?

I have a database using MySQL called "users".我有一个名为“用户”的使用 MySQL 的数据库。 In it are two tables.里面有两张桌子。 "first" and "second". “第一”和“第二”。

I take the users information from a form using JavaScript as an array of objects.我从使用 JavaScript 作为对象数组的表单中获取用户信息。

eg let usersInformation = [{"name":"james", "age":"30"}]例如let usersInformation = [{"name":"james", "age":"30"}]

How can I easily store each array of objects?如何轻松存储每个对象数组?

In the past I have created columns eg "name" and then stored the value of "name" in that column.过去我创建了列,例如“name”,然后在该列中存储“name”的值。

Is there a way to store objects in a MySQL database.有没有办法在 MySQL 数据库中存储对象。 I looked up the term ORM and thought that may be of help.我查了一下 ORM 一词,认为这可能会有所帮助。

You can use the JSON data type of MySQL.您可以使用 MySQL 的 JSON 数据类型。

mysql> create database user; 

mysql> use user
# Create a table with a json data type
mysql> create table user (json JSON); 

# Insert an array into the field
mysql> insert into user(json) values ('["first", "second", "third", "4th"]'); 

# Insert an object
mysql> insert into user(json) values('{"name": "Levi", "last": "Jr"}');

mysql> select * from user;
+-------------------------------------+
| json                                |
+-------------------------------------+
| ["first", "second", "third", "4th"] |
| {"last": "Jr", "name": "Levi"}      |
+-------------------------------------+
2 rows in set (0.00 sec)


You can use the JSON_EXTRACT to get some info from the field and filter it in the WHERE clause.您可以使用JSON_EXTRACT从字段中获取一些信息并在 WHERE 子句中对其进行过滤。

Here is how to use it: JSON_EXTRACT([field], [expression])) , [expression] being how you going to extract the info from the field.下面是如何使用它: JSON_EXTRACT([field], [expression])) , [expression] 是你将如何从字段中提取信息。

Ex.:前任。:

mysql> select * from user where JSON_EXTRACT(user.json, '$.name') = 'Levi';
+--------------------------------+
| json                           |
+--------------------------------+
| {"last": "Jr", "name": "Levi"} |
+--------------------------------+
1 row in set (0.00 sec)

mysql> select * from user where JSON_EXTRACT(user.json, '$[0]') = 'first';
+-------------------------------------+
| json                                |
+-------------------------------------+
| ["first", "second", "third", "4th"] |
+-------------------------------------+
1 row in set (0.00 sec)

Before send your object to the query convert it to json .在将您的对象发送到查询之前,将其转换为json If you need you can make your table field as MEDIUM TEXT如果您需要,您可以将表格字段设为MEDIUM TEXT

let usersInformation = [{"name":"james", "age":"30"}];
usersInformation = JSON.stringify(usersInformation);

Then send this to your query.然后将此发送到您的查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM