Issue with inserting data into MariaDB using NodeJS - javascript

const mariadb = require('mariadb/callback');
const connection = mariadb.createConnection({
host : 'localhost',
user : 'tudublin',
password : 'Tudublin#2020',
database : 'IOT',
timezone: 'Europe/Dublin',
});
connection.connect(err => {
if (err) {
console.log("not connected due to error: " + err);
} else {
console.log("connected ! connection id is " + connection.threadId);
}
});
connection.query("INSERT INTO observations VALUES (?, ?, ?, ?)", [2, 20, "oC", Date.now()], (err, result) => {
if (err) throw err;
console.log(result);
//log : { affectedRows: 1, insertId: 1, warningStatus: 0 }
}
);
MariaDB [IOT]> describe observations;
+-----------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+------------------+------+-----+---------+----------------+
| data_id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| sensor_id | int(10) unsigned | NO | MUL | NULL | |
| temp | int(11) | YES | | NULL | |
| temp_unit | varchar(30) | YES | | NULL | |
| dt_added | datetime | YES | | NULL | |
+-----------+------------------+------+-----+---------+----------------+
5 rows in set (0.003 sec)
Hi,
I am trying to insert data into my observations table. But it keeps displaying the error:
code: 'ER_WRONG_VALUE_COUNT_ON_ROW'
I created the table using the below command
CREATE TABLE observations (data_id INT unsigned not null auto_increment primary key,sensor_id INT unsigned not null, temp int, temp_unit VARCHAR(30), dt_added DATETIME);
&
ALTER TABLE observations ADD FOREIGN KEY (sensor_id) REFERENCES sensors(sensor_id);
Which I thought the way it's set up would be fine as I am only entering in 4 values and the other one being the data_id which is set as a primary key and auto_increments. Would anyone have any idea on why it shows the above error?
Thanks!

In INSERT INTO observations VALUES (?, ?, ?, ?) you omit the column names associated with the values, due to that you need to provide values for all columns, also the primary key (even so it has auto increment).
You generally should not rely only on the column order when inserting values but use the corresponding column names. This will prevent you from future problems in case the column order changes for some reason and allows you to omit the data_id column:
INSERT INTO `observations`(`sensor_id`, `temp`, `temp_unit`, `dt_added`) VALUES (?,?,?,?)

Related

ASCII Table does not format as I want it to be

I'm making a discord bot using MySQL, the database stores some usernames and passwords. I fetch the data from the table in MySQL to format it in an ASCII table. The expected output was to be like the image below. (edited it to look better)
.------------------------------------------------.
| Username | Password |
|----------------------|-------------------------|
| amonggers | no |
| no username for u | no |
| not even this one | no |
| no | no |
'------------------------------------------------'
But the bot forms the table like this.
.------------------------------------------------.
| Username | Password |
|----------------------|-------------------------|
| amonggers | no
|
| no username for u | no
|
| not even this one | no
|
| no | no |
'------------------------------------------------'
Edit: I also console logged it and the output is a bit better than the discord bot one.
.------------------------------------------------.
| Username | Password |
|----------------------|-------------------------|
|amonggers | no
|no username for u | no
|not even this one | no
| no | no |
'------------------------------------------------'
[![Console Log created][3]][3]
Heres the command code
client.on("messageCreate", async (message) => {
if (message.content.toLowerCase().startsWith("=list")) {
connection.query("SELECT * FROM rbinfo", (err, results) => {
if (err) {
console.log(err)
}
const ascii = require('ascii-table');
var table = new ascii()
table.setHeading('Username', 'Password')
results.forEach(ok => table.addRow(ok.Username, ok.Password))
});
}
});
Any help at all is appreciated, thanks.

Updating PostgreSQL data in javascript where ajax URL contains a single quote

Modifying data in PostgreSQL in javascript where URL contains a single quote
What would be the best way to approach this problem?
In some of these approaches, success has been printed out but there is no change in the database.
In the case where there is no single quote success would print and the database will update as well.
Attempts
first_name = D'Angelo
first_name = D%27Angelo
first_name = D\'Angelo
first_name = 'D''Angelo'
first_name = D\\\'Angelo
database
_______________________________
|first_name|last_name|is_present|
---------------------------------
| D'Angelo |Williams | false |
---------------------------------
| Georgia | Fritz | false |
---------------------------------
| Luca | O'Keefe | false |
_______________________________
file.js
modify_student_data = "D'Angelo: Williams :false" //this attempt will work for the row that contains Georgia
first_name = "D'Angelo";
last_name = "Williams";
is_present = "true";
$.ajax({ url:'/data/student_attendance/' + modify_student_data + "*" + first_name + ':' + last_name + ':'+ is_present,
success: function (result){
console.log("Success");
}
error: function (er){
console.log("error");
}
});
desired outcome
_______________________________
|first_name|last_name|is_present|
---------------------------------
| D'Angelo |Williams | true |
---------------------------------
| Georgia | Fritz | false |
---------------------------------
| Luca | O'Keefe | false |
_______________________________

How to insert only distinct values to a MySQL table?

I'm using Google Apps Script to update a MySQL table from Google Cloud SQL and I don't want to insert duplicate values, for example:
If I have the following table with a record
+----+--------+-----------+-------+
| id | name | address | phone |
+----+--------+-----------+-------+
| 1 | John | Somewhere | 022 |
+----+--------+-----------+-------+
| 2 | Snow | North | 023 |
+----+--------+-----------+-------+
Then I should not be able to execute a query that inserts a new record where
name=John,
address=Somewhere,
phone=022
or
name=Snow,
address=North,
phone=023
This is my current code that inserts new records to the database:
var stmt = conn.prepareStatement('INSERT INTO entries '
+ '(name, address, phone) values (?, ?, ?)');
stmt.setString(1, "John");
stmt.setString(2, "Snow");
stmt.setString(3, 022);
stmt.execute();

Convert javascript value to binary to be placed into mysql

I have a column in my mysql table of type binary(password). Within my object:
{
password: request.password
};
Each value in the object is a string. How do I convert the value for password to binary to be placed into the mysql row?
+------------+--------------+------+-----+-------------------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+-------------------+-------+
| password | binary(16) | NO | PRI | | |
+------------+--------------+------+-----+-------------------+-------+
var password = "test";
var result = "";
var i = password.length;
while (i--) {
result += (password.charCodeAt(i) >>> 0).toString(2);
}
console.log(result);

How to auto-update date field on firebase using ng-grid

I have a date field (called: lastUpdate) on a firebase db.
How could I update that field using ng-grid on change from another field (say a separte field called: notes)?
Im using the following code to update my records on edit:
var cellEditableTemplate = "<input ng-class=\"'colt' + col.index\"
ng-input=\"COL_FIELD\" ng-model=\"COL_FIELD\"
ng-change=\"updateEntity(col,row)\"/>"
$scope.updateEntity = function (col, row) {
$scope.dblogs.$save(row.entity.$id);
};
Posted Below is my sample db being used:
uniqueIDajsdljfasdjfajsdf;jasdj
|
|
--->ticket
| |
| -->completed: true
| |
| -->dateUpdated: "(last activity date/time)"
| |
| -->notes: "need to update logger code today!"
|
---->username: "vr"

Categories