javascript - 有没有办法将对象存储在 mySQL 数据库中?
问题描述
我有一个使用 MySQL 的数据库,称为“用户”。里面有两张桌子。“第一”和“第二”。
我使用 JavaScript 作为对象数组从表单中获取用户信息。
例如let usersInformation = [{"name":"james", "age":"30"}]
如何轻松存储每个对象数组?
过去,我创建了列,例如“name”,然后将“name”的值存储在该列中。
有没有办法将对象存储在 MySQL 数据库中。我查找了 ORM 一词,并认为这可能会有所帮助。
解决方案
您可以使用 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)
您可以使用JSON_EXTRACT
从字段中获取一些信息并在 WHERE 子句中对其进行过滤。
以下是如何使用它:JSON_EXTRACT([field], [expression]))
, [表达式] 是您从字段中提取信息的方式。
前任。:
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)
推荐阅读
- java - 如何从 Flux 中选择每个组的最大项目
- javascript - 如何将json按连续值分组到一个数组中
- javascript - 单击数据表行下拉列表中的选项时调用 js 函数并发送一些数据
- image-processing - 将 3-D MRI 图像轴转置到不同的图像视图
- react-native - Reactive Native - 提供给样式表的无效道具“”
- javascript - 使用新的 `li` 元素扩展 HTML ul/li,缺少事件
- django - 如何从 Django 生成一个监听器?
- visual-studio-code - 如何在 VS Code 中启用新的笔记本编辑器
- python-3.x - How can I create a graph from dataframe columns where nodes = (user_id, friend_id) and edge = (IsFriend, value is 0/1)
- kotlin - 从android和协程中的流中收集值的正确方法