How to Take Just Data Without Column Names in NodeJS with MySql - mysql

When I want to take data from mysql in NodeJS, it results like
RowDataPacket { name : 'John', marks : 56}
But I want to take this data without column names or other things. I need to use just NodeJS for this problem. I saw some JSON solutions but I can’t do this cause of my program.

The result of a 'SELECT' query will be an array of objects. And each object defines a row.
You can either iterate through the array and use the key to access its value like results.forEach( row => { row[key] })
or if your result returns a single row, then you can access the object as results[0].

You need to set an index and then obtain the value.
For example if you are storing your response in a variable called results.
Use the following:
x = results[0].name;
Then you can use this variable/name further in your program.

Related

how to select rows where a specific string column matches at least one value inside a json array?

SELECT name FROM accounts WHERE Name in ("name1","name2");
the values are being sent inside a json array
["name1","name2"]
currently i just convert the array into json string and remove the first and last characters
"name1","name2"
but could i just keep the array intact? i tried json_contains
SELECT name FROM accounts WHERE JSON_CONTAINS(name,'["name1","name2"]');
my understanding as to which why that didn't work is because name column isn't json string array
Core issue is you can't "prepare" flex statements without some sort of preprocessing.
Generally you'll want to do input validation etc, on the application side regardless, and then use some sort of pre-constructor if you're not using an ORM.
ie:
$values = ["name1", "name2"];
// Validation should happen here
$inputs = substr(str_repeat("?,", count($values)), 0, -1);
$bind = str_repeat("s", count($values));
$sqli = "SELECT name FROM accounts WHERE Name in ($inputs);";
...
$stmt->bind_param($bind, ...$values);
...
You can use the same principal for PDO as well, but regaredless you're gunna want to handle the validation layer on the application side, and there is no "easy" way to inject "IN" statements into prepared SQL.

Extract certain members of JSON array in MySQL

I have a table in MySQL where each row contains JSON returned from another system. The JSON will look something like:
[{"userId": "Dave"},{"userId": "Mary", "errorCode" : "DB Fail"}, {"userId": "Lorenza", "errorCode": "Web Error"}]
and I'm only interested in the members of the array containing an error code. In the future, these will be parsed into seperate rows of their own table, but in the meantime does MySql offer a way to extract only these with an errorCode?
I can use JSON_EXTRACT to extract the errorCodes only
JSON_EXTRACT(jsonData, '$[*].errorCode') AS errorCodes
but I really want the rest of the member (userId in the example above)
You could use the JSON_CONTAINS function to find the records with errorCode and then then use JSON_EXTRACT on those records. Put the JSON_CONTAINS in the where clause
I don't think you could do this with a single query without known boundaries of the number of elements, but you could use a stored procedure to run a loop.
e.g. each iteration runs LOCATE to find the position of "errorCode", and uses that location to run SUBSTR and/or SUBSTRING_INDEX to get the userid value and append it to another variable. The looped variable would just be the offset used in the LOCATE query.

Insert/update JSON into Postgresql column WHERE myvar = myval

I'm trying to insert JSON into a Postgresql column who's data type is JSON, but I'm having trouble finding how I can do this. This is as far as I've gotten but it's not correct because it just overwrites it every time, instead of adding a new key pair.
I'm using pg-promise node module to perform these queries. Here's what I have so far:
db.query("UPDATE meditation_database SET completed=$1 WHERE user_id=$2", [{myVar : true}, user_id]);
Also 'myVar' should be updated to the variable value, but instead it treats it as a string. How can I get the actual value of 'myVar' instead of it being treated literally.
Thanks,
I'm trying to insert JSON into a Postgresql column who's data type is JSON, but I'm having trouble finding how I can do this.
By executing this:
db.query("INSERT INTO meditation_database(completed, user_id) VALUES($1, $2)",
[{myVar : true}, user_id]);
Also 'myVar' should be updated to the variable value, but instead it treats it as a string. How can I get the actual value of 'myVar' instead of it being treated literally.
myVar is serialized into JSON as a string, that's the proper JSON format for property names, and is the only format that PostgreSQL will accept.
This is as far as I've gotten but it's not correct because it just overwrites it every time, instead of adding a new key pair.
If you are asking how to update JSON in PostgreSQL, this question has been answered previously, and in great detail: How do I modify fields inside the new PostgreSQL JSON datatype?

MySQL getting JSON value

In my MySql players table I have a column called achievements and it is a text field which in this particular row has this value:
[
{
"value":11,
"globalID":23000000
},
{
"value":11,
"globalID":23000001
},
{
"value":11,
"globalID":23000002
},
...
{
"value":6044730,
"globalID":23000065
}
]
Near the bottom of the array you can see this object:
{
"value":48,
"globalID":23000062
},
I need to be able to parse the value field and show it as a warhero field. But how can I do this? The globalID will stay the same but the value changes. And because the globalID is after the value value I can't use what was used in this post: https://stackoverflow.com/a/21596032/4942382
What SQL query would I need to run to get that value?
Thanks!
The design of a table does not even meet the first normalisation level if it stores a non-atomic value in a single column, which is the case with this type of JSON encoded values.
Now if you have no access to the JSON functions available to MySql version 5.7+, and your globalID has a fixed number of digits, then you could do some string matching as follows.
For example, if you need the value that goes with globalID 23000062, then you could do this:
SELECT players.*,
CAST(
SUBSTRING_INDEX(
SUBSTRING_INDEX(achievements, '"globalID":23000062', 1),
'"value":',
-1
)
AS UNSIGNED) AS json_extracted_value
FROM players
WHERE INSTR(achievements, '"globalID":23000062') > 0
But really, you should seriously consider redesigning your database.
You should have never saved the JSON in your table, you already broke the rules of relational database design.
mysql cannot make sense of the data, so no SQL query will help you, you have 2 options:
Fix your database design, create tables to hold that data instead of JSON
Fetch the data, decode the JSON, and do all type of manipulations and hacks to get your desired value.

MySQL increment value in a text field

Say I have a text field with JSON data like this:
{
"id": {
"name": "value",
"votes": 0
}
}
Is there a way to write a query which would find id and then would increment votes value?
I know i could just retrieve the JSON data update what I need and reinsert updated version, but i wonder is there a way to do this without running two queries?
UPDATE `sometable`
SET `somefield` = JSON_REPLACE(`somefield`, '$.id.votes', JSON_EXTRACT(`somefield` , '$.id.votes')+1)
WHERE ...
Edit
As of MySQL 5.7.8, MySQL supports a native JSON data type that enables efficient access to data in JSON documents.
JSON_EXTRACT will allow you to access a particular JSON element in a JSON field, while JSON_REPLACE will allow you to update it.
To specify the JSON element you wish to access, use a string with the format
'$.[top element].[sub element].[...]'
So in your case, to access id.votes, use the string '$.id.votes'.
The SQL code above demonstrates putting all this together to increment the value of a JSON field by 1.
I think for a task like this you're stuck using a plain old SELECT followed by an UPDATE (after you parse the JSON, increment the value you want, and then serialize the JSON back).
You should wrap these operations in a single transaction, and if you're using InnoDB then you might also consider using SELECT ... FOR UPDATE : http://dev.mysql.com/doc/refman/5.0/en/innodb-locking-reads.html
This is sort of a tangent, but I thought I'd also mention that this is the type of operation that a NoSQL database like MongoDB is quite good at.