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.
Related
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.
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") /* ... */
This 2d array can be of any length so if for example the array is
var my_2D_Array =
[['jack',22,'student'],
['Bob',45,'doctor'],
['bucky',30,'unelployed']]
// currently I am using this but it isn't working properly
for(i=0;i<my_2D_Array.length;i++){
clientChart.run(`INSERT INTO HP2255 VALUES (?, ?, ?)`,my_2D_Array[i],(err)=>{
console.log('err' + err)
})
Is it possible to insert an array like this into the database with out using a for loop
I am really new to programming in general and if there is anything that I am missing than please help me out
Without knowing more about your setup/table definition and based on the Usage presented in the repo I would guess something like the following:
const my_2D_Array = [
['jack', 22, 'student'],
['Bob', 45, 'doctor'],
['bucky', 30, 'unelployed'],
];
// explicitly declare columns (it may work without, but is more fragile and less clear)
const stmt = clientChart.prepare('INSERT INTO HP2255 (name, age, job) VALUES (?, ?, ?)');
for (const row of my_2D_Array) {
stmt.run(...row); // spread each sub-array to pass the individual elements
}
stmt.finalize();
Creating a bike rent application and implementing addBike() to database. addCustomer() worked with this code, but I think it is because it has no foreign keys. How do I Insert Into database when half the table is foreign keys?
Thank you!
newbike.js:
add() {
bikeService.addBike(
this.wheelsize,
this.frame,
this.gears,
this.typeId,
this.location,
this.orderId,
id => {
history.push('/bike/' + id);
this.props.history.push('/regbike');
}
);
}
}
services.js:
connection.query(
'insert into Bike (wheelsize, frame, gears, typeId, statusId, location, orderId) values (?, ?, ?, ?, ?, ?, ?)',
[wheelsize, frame, gears, typeId, statusId, location, orderId],
(error, results) => {
if (error) return console.error(error);
success(results.insertId);
}
);
}
export let bikeService = new BikeService();
You should disable constraint check before insert and reenable it afterwards (If you want to insert loads of data)
SET FOREIGN_KEY_CHECKS=0;
and then when you're done
SET FOREIGN_KEY_CHECKS=1;
or just INSERT IGNORE
"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"
It all depends on what you want to achieve
So it would look like this:
Disable the constraint checks.
Insert all the data you have to all your related tables
Enable the constraint checks.
a) verify that you didn't loose any data.
b) verify that the constraints are actually enabled
I'm working on a small Phonegap Project, and have problems with finding the right syntax to insert into a WebSQL database. I'm reading a jSON response from an API and try to cache it to a WebSQL / SQLite database but always get an error message. The database is created, the table also... problem is the insert.
For inserting the different Rows into the database I iterate over my JSON. All variables are set and shown when I display them with console.log. What am I doing wrong?
songdata = JSON.parse(songdata);
// JSON Gespielte Songs für ALLE Clubs abfragen, in SQLite speichern, und bei "success" weiter an den clubboxstyler weiterleiten
db = window.openDatabase("database.db", "1.0", "Demo", -1);
db.transaction(function(tx){
tx.executeSql('CREATE TABLE IF NOT EXISTS activity_stream (id integer primary key autoincrement, band text, clubID integer, time text, title text)');
for (var kay in songdata)
{
var Xband = songdata[kay].band;
var XclubID = songdata[kay].clubID;
var Xtime = songdata[kay].time;
var Xtitle = songdata[kay].title;
console.log(Xtitle);
tx.executeSql('INSERT INTO activity_stream (id, band, clubID, time, title) VALUES (1, ?, ?, ?, ?), [1, Xband, XclubID, Xtime, Xtitle]');
}
}, function(e) {
console.log("ERROR: " + e.message);
});
Thank you for you help! Much appreciated.
Well, in your code snippet you are explicitly setting the same id (that equals '1') to each row you are inserting. That can't work, as primary keys need to differ, right? :)
The thing with autoincrementing columns is that you don't provide value for them, they are set up for you automatically. So just omit the 'id' column when inserting, like this:
tx.executeSql('INSERT INTO activity_stream (band, clubID, time, title) VALUES (?, ?, ?, ?), [Xband, XclubID, Xtime, Xtitle]');