In this second part of the multiple part post, I am going to show how to insert data into table in SQL Server.
Happy Coding ! | dhandrohit@gmail.com
knex("dept")
.insert({
deptno: 50,
dname: "New Department",
loc: "Test Location"
}).catch(function(err) {
// All the error can be checked in this piece of code
console.log(err);
}).finally(function() {
// To close the connection pool
knex.destroy();
});
console.log("Record Inserted");
If you run this code, one record will be created in the Table with Deptno: 50. The following result is shown as per data in my table, if we run the Select query. { DEPTNO: 10, DNAME: 'ACCOUNTING', LOC: 'NEW YORK' }
{ DEPTNO: 20, DNAME: 'RESEARCH', LOC: 'DALLAS' }
{ DEPTNO: 30, DNAME: 'SALES', LOC: 'CHICAGO' }
{ DEPTNO: 40, DNAME: 'OPERATIONS', LOC: 'BOSTON' }
{ DEPTNO: 50, DNAME: 'New Department', LOC: 'Test Location' }
We can also run Knex insert query in the manner where if the table has an AutoIncrement Id column, we can capture the new Id when generated through Insert command. knex('depts').insert({
dname: "New Department",
loc: "Test Location"
})
.returning('id')
.then((id) => {
console.log(id);
});
In the above example, we are able to return the Id after the insert Query is successfully ran.Happy Coding ! | dhandrohit@gmail.com
Comments