INSERT INTO table VALUES float string from postman input - javascript

I'm trying to create a new course row into my Courses database in postman and I cannot get the syntax correct.
I've got 159 values that need to be added into a single course. Any chance I can summarise them instead of having to write down all the values?
Currently this is my query:
const addCourse = "INSERT INTO courses VALUES (value1 'value2','value3', 'value4', 'value5', 'value6', 'value7', 'value8', 'value9', 'value10', 'value11', 'value12', 'value13', 'value14', 'value15', 'value16', 'value17', 'value18', 'value19', 'value20', 'value21', 'value22', 'value23', 'value24', 'value25', 'value26', 'value27', 'value28', 'value29', 'value30', 'value31', 'value32', 'value33', 'value34', 'value35', 'value36', 'value37', 'value38', 'value39', 'value40', 'value41', 'value42', 'value43', 'value44', 'value45', 'value46', 'value47', 'value48', 'value49', 'value50', 'value51', 'value52', 'value53', 'value54', 'value55', 'value56', 'value57', 'value58', 'value59', 'value60', 'value61', 'value62', 'value63', 'value64', 'value65', 'value66', 'value67', 'value68', 'value69', 'value70', 'value71', 'value72', 'value73', 'value74', 'value75', 'value76', 'value77', 'value78', 'value79', 'value80', 'value81', 'value82', 'value83', 'value84', 'value85', 'value86', 'value87', 'value88', 'value89', 'value90', 'value91', 'value92', 'value93', 'value94', 'value95', 'value96', 'value97', 'value98', 'value99', 'value100', 'value101', 'value102', 'value103', 'value104', 'value105', 'value106', 'value107', 'value108', 'value109', 'value110', 'value111', 'value112', 'value113', 'value114', 'value115', 'value116', 'value117', 'value118', 'value119', 'value120', 'value121', 'value122', 'value123', 'value124', 'value125', 'value126', 'value127', 'value128', 'value129', 'value130', 'value131', 'value132', 'value133', 'value134', 'value135', 'value136', 'value137', 'value138', 'value139', 'value140', 'value141', 'value142', 'value143', 'value144', 'value145', 'value146', 'value147', 'value148', 'value149', 'value150', 'value151', 'value152', 'value153', 'value154', 'value155', 'value156', 'value157 ', 'value158' )"
This is my courseController code:
const addCourse = (req, res) => {
console.log(req.body);
const { id_curso } = req.body;
//check Curso exists
pool.query(queries.checkIdCursoExists, [id_curso], (error, results) => {
if (results.rows.length) {
res.send("Este curso ja existe.");
}
// add course
pool.query(queries.addCourse),
(error, results) => {
if (error) throw error;
res.status(201).send("Curso criado com sucesso");
};
});
};
The problem I encounter is this error message whether I have value1 in quotes or not:
error: type "value1" does not exist'
The course is not posted onto my database.

The path to your answer lies in your INSERT statement. I guess your courses table has 159 columns in it. (That is a great many columns and may suggest the need to normalize your table. SQL handles multiple-row data more efficiently than multiple-column data where it makes sense to do so. But you did not ask about that.)
The INSERT syntax is either this:
INSERT INTO tbl (col1, col2, col3) VALUES (const, const, const);
or this:
INSERT INTO tbl VALUES (const, const, const);
The first syntax allows you to insert a row without giving values for every column in the table. You use the second syntax. It requires you to give one constant value for each column of your table. But your insert looks like this:
INSERT INTO courses VALUES (value1 'value2', ... , 'value158' )"
I see some problems with this.
You only have 158 values, but your question says you have 159.
value1, the first value in your list, isn't a constant.
You need a comma after your first value.
All your value constants are text strings. Yet you mentioned float in the title of your question.

Related

NodeJs PG query not executed as expected

I have the following, AWS lambda code inserting into a table:
let queryString = "INSERT INTO orders(order_id, channel, channel_order_id, channel_order_code, channel_merchant, merchant, min_time, max_time, delivery_expected_time, status, observations, total, sub_total, voucher_discount, delivery_tax, fk_customer_id, fk_address_id, order_contact, order_type, payment_pending, payment_prepaid, channel_merchant_id, order_timming, picker, delivered_by, delivery_obs, takeout, takeout_date_time, takeout_obs, indoor, table)VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28, $29, $30, $31) RETURNING *";
const newOrder = await client.query(queryString, [order_id, channel, channel_order_id, channel_order_code, channel_merchant, merchant, min_time, max_time, delivery_expected_time, status, observations, total, sub_total, voucher_discount, delivery_tax, fk_customer_id, fk_address_id, order_contact, order_type, payment_pending, payment_prepaid, channel_merchant_id, order_timming, picker, delivered_by, delivery_obs, takeout, takeout_date_time, takeout_obs, indoor, table], (err, res) => {
if(err)console.log(res, err)
});
And then another insert in a table that has a foreign key that references an order(order_id), which should be the one being created at the first insert
I'm getting an error, on the second insert, that says that the order(order_id) does not exist. So it means that the order is not being created, the first insert is not being executed, but nothing is being caught in the console.log(err)
Now the interesting part. If I remove the table column from the first insert everything goes as expected
If I console.log(table) I get null
And the column is NotNull = False, which means that it can be null, just like as other values I'm using on the insert
Any hint on what could be happening here? Is there a limit of how many columns I can have on an insert?
table is a keyword in Postgres.
If you're insisting on continuing to maintain a column in your schema with the name table (not advisable), you'll need to pass it in quotes when referencing it:
INSERT INTO orders ("table") /* ... */

How to insert values from JSON data with multiple objects into rows in MySQL?

I can store a value in a JSON data with one object into MySQL data base, like this:
var data = '{"sensorvalue":"96"}'
const jsdata = JSON.parse(data);
connection.query("INSERT INTO `nodes`(`sensorvalue`) VALUES ('"+jsdata.sensorvalue+"')", (err, res) => {
console.log("counter record inserted");
});
The output:
id
sensorvalue
1
96
However, I want to store values in a JSON data with two or more objects, like this:
var data = '[{"sensorvalue":"96"},{"sensorvalue":"98"}]'
But, it stores it as a undefined in row in table.
The expected output:
id
sensorvalue
1
96
2
98
I have seen this questionbefore but I don't know how this could help me because in that question is about array of arrays not a JSON data with multiple objects.
How could I solve this, please?
It's an array, you need to loop over it.
You also shouldn't substitute values directly into the SQL, use parametrized queries.
const jsArray = JSON.parse(data);
jsArray.forEach(jsdata =>
connection.query("INSERT INTO `nodes`(`sensorvalue`) VALUES (?)", [jsdata.sensorvalue], (err, res) => {
console.log("counter record inserted");
})
);
The node.js MySQL connector also allows you to use a 2-dimensional array to insert values in multiple rows at once. See How do I do a bulk insert in mySQL using node.js
const sensorValues = JSON.parse(data).map(el => [el.sensorvalue]);
connection.query("INSERT INTO `nodes`(`sensorvalue`) VALUES ?", sensorValues, (err, res) => {
console.log(`${sensorValues.length} counter records inserted`);
});

not able to add values to mysql table from node

I want to insert data into my table, I'm able to do it in node.js when I just put strings in my values.
var sql = INSERT INTO teachers (full_name, school, email) VALUES ('alex','bennet','alex#bennet.com);
However, when I put the value created by POST method, it gives me a syntax error.
var sql = INSERT INTO teachers (full_name, school, email) VALUES (${teacher.name},${teacher.school},${teacher.email});
code: 'ER_BAD_FIELD_ERROR',
errno: 1054,
sqlMessage: "Unknown column 'alex' in 'field list'",
sqlState: '42S22',
index: 0,
sql: "INSERT INTO teachers (full_name, school, email) VALUES (alex,bennet,alex#bennet.com) "
I dont know why it assumes alex as a column name and not value.
The immediate problem is that you are intercalating raw unescaped strings into your insert query, which won't work, since string literals in MySQL need to be escaped by quotes. The best fix here is to use a prepared statement:
let stmt = `INSERT INTO teachers (full_name, school, email) VALUES (?, ?, ?)`;
let pals = ['alex', 'bennet', 'alex#bennet.com'];
connection.query(stmt, vals, (err, results, fields) => {
if (err) {
return console.error(err.message);
}
});
You have to enclose the string with single quotes to specify as string. So your code should be like this,
var sql = INSERT INTO teachers (full_name, school, email) VALUES ('${teacher.name}','${teacher.school}','${teacher.email}');
Hope it will solve your issue.

delete user from json table in js

So I'm a beginner to js and I have a table of users in a json file and I'm making an account delete feature. I have a find set up to find the user and it works fine but I can't figure out how to make it delete the user from the file, any help would be appreciated!
Json:
{
"users": [
{
"name": "ImBattleDash",
"Id": "780748c5d4504446bbba3114ce48f6e9",
"discordId": "471621420162744342",
"dateAdded": 1548295371
}
]
}
JS:
function findJson() {
fs.readFile('./linkedusers.json', 'utf-8', function (err, data) {
if (err) message.channel.send('Invalid Code.')
var arrayOfObjects = JSON.parse(data)
let findEntry = arrayOfObjects.users.find(entry => entry.discordId == myCode)
let linkEmbed = new Discord.RichEmbed()
.setTitle('Account unlinked!')
.setDescription('Link your account by friending "BattleDash Bot" on Fortnite and then input the code you get messaged by typing "!link <code>"!')
.setColor('#a900ff');
message.channel.send({embed: linkEmbed});
})
}
EDIT: Not sure if it's an array or a table I don't know a lot about json
You need to use:
Array#find to find a given user by some given criteria.
Array#indexOf to get the index of the found user in users
Array#splice to drop one element starting from the index given by Array#indexOf:
const input = {
"users": [
{
"name": "ImBattleDash",
"Id": "780748c5d4504446bbba3114ce48f6e9",
"discordId": "471621420162744342",
"dateAdded": 1548295371
}
]
}
const removeUser = (criteria, users) =>
users.splice (users.indexOf (users.find (criteria)), 1)
removeUser (
({ Id, discordId }) =>
Id == '780748c5d4504446bbba3114ce48f6e9'
&& discordId == '471621420162744342',
input.users
)
// Output: 0 <-- User has been removed!
console.log(input.users.length)
About persisting the change, it's just about calling JSON.stringify (input) and then just write the contents to the desired output file. See this other Q&A: Writing files in Node.js
With great help from Cat and Matias I came up with this code that works!
function findJson() {
fs.readFile('./linkedusers.json', 'utf-8', function (err, data) {
if (err) message.channel.send('Invalid Code.')
var arrayOfObjects = JSON.parse(data)
let findEntry = arrayOfObjects.users.find(entry => entry.discordId == myCode)
const input = arrayOfObjects;
const removeUser = (criteria, users) =>
users.splice (users.indexOf (users.find (criteria)), 1)
removeUser (
({ Id, discordId }) =>
Id == findEntry.Id
&& discordId == findEntry.discordId,
input.users
)
console.log('unlinked')
fs.writeFile('./linkedusers.json', JSON.stringify(arrayOfObjects, null, 4), 'utf-8', function(err) {
if (err) throw err
console.log('Done!')
})
let linkEmbed = new Discord.RichEmbed()
.setTitle('Account unlinked!')
.setDescription('Link your account by friending "BattleDash Bot" on Fortnite and then input the code you get messaged by typing "!link <code>"!')
.setColor('#a900ff');
message.channel.send({embed: linkEmbed});
})
}
Here's a quick tutorial for you:
"Users" would be either an array (using []) or a javascript object (using {}), your choice. There won't be any actual tables unless you use a database instead of a JSON file (although if your JSON expression is as simple as your example, you could almost think of it as a table.) -- And actually, a third option would be to use the javascript Map type, which is like a beefed-up object, but I won't address that here.
While using an array would make it a bit easier to retrieve a list of data for all users (because arrays are simpler to iterate through), using an object would make it considerably easier to retrieve data for a single user (since you can directly specify the user you want by its key instead of needing to loop through the whole array until you find the one you want.) I'll show you an example that uses an object.
The individual user in your sample code is an example of a javascript object. JSON lets you convert an object to a string (for storage, I/O, and human readability) and back to an object (so javascript can understand it). You use the JSON.stringify() and JSON.parse() methods, respectively for these conversions. The string has to be JSON-formatted or this won't work, and your example is almost in JSON format.
To comply with JSON formatting, you could structure a Users object as follows. (Of course we're looking at the stringified version because mere humans can't easily read an "actual" javascript object):
"Users": { // Each individual user is a property of your users object
"780748c5d4504446bbba3114ce48f6e9": // The Id is the key in the "key/value pair"
{ // The individual user object itself is the value in the key/value pair
// Id is duplicated inside user for convenience (not necessarily the best way to do it)
"id": "780748c5d4504446bbba3114ce48f6e9",
"name": "ImBattleDash", // Each property of the user is also a key/value pair
"discordId": "471621420162744342", //Commas separate the properties of an object
"dateAdded": "1548295371" // All property values need double quotes for JSON compatibility
}, // Commas separate the properties (ie the individual users) of the users object
"446bbba3114ce48f6e9780748c5d4504": // This string is the second user's key
{ // This object is the second user's value
"id": "446bbba3114ce48f6e9780748c5d4504",
"name": "Wigwam",
"discordId": "162744342471621420",
"dateAdded": "1548295999"
}
}
Once you retrieve the string from storage, you convert it to an object and delete a user as follows. (This is broken down into more steps than necessary for clarity.):
let usersObject = JSON.parse(stringRetrievedFromFile);
let userId = "780748c5d4504446bbba3114ce48f6e9";
let userToModifyOrDelete = usersObject[userId];
delete userToModifyOrDelete;
To change the user's discordId instead, you would do:
let discordId = userToModifyOrDelete.discordId; // Not necessary, just shows how to retrieve value
let newDiscordId = "whateverId";
userToModifyOrDelete.discordId = newDiscordId;
And you'd convert the object back into a string to store in your file with:
JSON.stringify(usersObject);
Hopefully that's almost all you need to know about JSON!

node-mssql Transaction insert - Returning the inserted id..?

I'm using node-mssql 3.2.0 and I need to INSERT INTO a table and return the id of the inserted record.
I can successfully use sql.Transaction() to insert data, but the only parameters given to callbacks (request.query() and transaction.commit()) are:
const request = new sql.Request();
request.query('...', (err, recordset, affected) => {});
const transaction = new sql.Transaction();
transaction.commit((err) => {});
So recordset is undefined for INSERT, UPDATE and DELETE statements, and affected is the number of rows affected, in my case 1.
Does anyone know a good way to obtain an inserted records id (just a primary key id) after a transaction.commit() using node-mssql..?
Instead of just doing an INSERT INTO... statement, you can add a SELECT... statement as well:
INSERT INTO table (...) VALUES (...); SELECT SCOPE_IDENTITY() AS id;
The SCOPE_IDENTITY() function returns the inserted identity column, which means recordset now contains the id:
const request = new sql.Request();
request.query('...', (err, recordset, affected) => {});
I don't think request.multiple = true; is required, because although this includes multiple statements, only one of them is a SELECT... and so returns.
So the answer was SQL related and is not specific to node-mssql.
I know this question has accepted answer.
I made the following way:
let pool = await sql.connect(config);
let insertItem = await pool.request()
.input('ItemId',sql.NVarChar, 'itemId1234')
.input('ItemDesc',sql.NVarChar, 'nice item')
.query("insert into itemTable (Id, ItemId,ItemDesc) OUTPUT INSERTED.ID
values (NEWID(), #ItemId, #ItemDesc);
var insertedItemId = insertItem.recordset[0].ID
This adds unique identifier to data that is saved to db (if table is created so)
create table itemTable(
Id UNIQUEIDENTIFIER primary key default NEWID(),
ItemId nvarchar(25),
ItemDesc nvarchar(25)
)

Categories

Resources