How to Insert Into table with multiple foreign keys in React? - javascript

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

Related

INSERT INTO table VALUES float string from postman input

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.

Insert a 2d array as multiple rows in a SQLite database using nodejs

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();

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.

How to insert in WebSQL / Phonegap SQLite with auto increment?

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]');

Reading info from sqlite database, Syntax? How do I use it in html5 webapp?

I have a webapp that I'm building, and have just started with SQLite. I have been able to create my form, open the database I created, create the table, and fields i need, and enter data into the fields.
Now I'm trying to read the data back out with a SELECT statement, to show it on screen and as a list of the columns. I just don't know the syntax for the SELECT statemnt in javascript or HTML5 beyond
'SELECT * FROM MyTable'...I know it can be done, just need some help with the syntax of getting the results onto the screen.
I start with this.
var db = window.openDatabase('TabOrder', '', 'Bar Tab Orders', 2500000);
function insertDrinks(category, drinkname, our_cost, cust_cost){
db.transaction(function(tx){
tx.executeSql('INSERT INTO Drinks (category, drinkname, our_cost, cust_cost) VALUES (?, ?, ?, ?)', [category, drinkname, out_cost, cust_cost]);
});
}
$(document).ready(function() {
db.transaction(function(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS Drinks(id INTEGER PRIMARY KEY Autonumber, category TEXT, drinkname TEXT, our_cost FLOAT(6,2), cust_cost FLOAT(7,2))', []);
});
});
I later have this....
View Cat / Drink List
function readDrinks(id, category, drinkname, our_cost, cust_cost){
db.transaction(function(tx) {
tx.executeSql('SELECT * FROM Drinks', [id, category, drinkname, our_cost, cust_cost]);
});
document.write(id, category + " are the categories.");
}
I just tried to piece it together, and have no idea what i'm doing with it beyond the basic SQL.
Any help is greatly appreciated...and this is for a client side DB, not one connecting to the web.
thanks....
See the spec and this Apple tutorial. In short, you need to add data and error callbacks. Also, you should be passing an empty array (or null) because your query has no parameters.
db.transaction(function(tx) {
tx.executeSql('SELECT * FROM Drinks',
[],
function(tx, results)
{
// results is a http://dev.w3.org/html5/webdatabase/#sqlresultset .
// It has insertId, rowsAffected, and rows, which is
// essentially (not exactly) an array of arrays.
},
function(tx, error)
{
}
);
});
It's up to you whether to use named or anonymous functions.
EDIT: I made a working demo at http://jsfiddle.net/WcV6Y/7/ . It's tested in Chrome 5.0.375.70.
try something like this tx.executeSql('SELECT * FROM foo', [], function (tx, results) {
var len = results.rows.length;
for (var i = 0; i < len; ++i) {
var obj = results.rows.item(i);
alert(obj);
}
});
also see this for short tutorial http://html5doctor.com/introducing-web-sql-databases/

Categories

Resources