MS SQL, JavaScript, HTML table connection - javascript

Data from MS SQL is showing in JavaScript in Output (as i wanted) when i run the code. Now, I want to show my data (name, id) in HTML via localhost. Do you have any clues how to make it work?I don't know where to start, because i'm a beginner in javascript so i tried only the simpliest ways like <script src="index.js"></script> but it obviously didn't work.
If it helps, I used https://www.youtube.com/watch?v=ePi0HIz-6pE this to make my JS work.
You asked me for more code from index.js so here it is:
const sql = require('mssql/msnodesqlv8');
var config={
database: 'name',
server: 'name',
driver: 'msnodesqlv8',
options:{
trustedConnection:true
}
};
sql.connect(config,function(err){
if(err){
console.log(err);
}
var request = new sql.Request();
request.query('select * from animal.species', function(err,recordSet){
if(err){
console.log(err)
}else{
console.log(recordSet)
}
});
});

Related

Insert multiple records into SQL Server (mssql) in node.js

I am migrating a piece of code from mysql to mssql package of nodejs, in which its required to insert multiple rows.
Here's the sample code I am using for testing:
const db = require('mssql');
let config = {
user: 'salim',
password: 'admin',
server: 'LAPTOP-JK45R', // You can use 'localhost\\instance' to connect to named instance
database: 'master',
}
var pool;
//initialize connection pool
var connectPool = initializeConnectionPool();
function initializeConnectionPool() {
pool = new db.ConnectionPool(config);
pool.on('error', (err) => {
logger.error(err);
});
return pool.connect();;
}
connectPool.then(async () => {
let connection = await pool.request();
console.log('Got pool connection...');
var q = "INSERT INTO Person (name, address) VALUES ?";
var values = [
['John', 'Highway 71'],
['Peter', 'Lowstreet 4'],
['Amy', 'Apple st 652'],
['Hannah', 'Mountain 21']
];
let result = await connection.query(q,[values]);
console.log(`Result: ${JSON.stringify(result)}`);
});
Its giving me error:
RequestError: Incorrect syntax near '?'.
I couldn't find any thing on official npm page of mssql, so I have been trying this: Insert multiple columns and rows into SQL Server with node js
In my code I am just using pool.
I also couldn't find how to log queries using this package, so couldn't figure out what the query is being formed.
It would be great to know any of the solution.
The ? is a way to pass parameter in mysql
In mssql it seem to be like ${entries}
refer to How to pass parameter to mssql query in node js

mongo database doesn't show up in command line

I don't understand why my mongo db isn't showing up when I run "show databases" in the command line. I see other mongo db's I created in the past, but not the current one. Here is my code: (using mongoose ORM):
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/fuelTracker');
var Schema = mongoose.Schema;
var fuelSchema = new Schema({
time : { type : Date, default: Date.now },
miles : Number,
gallons: Number
});
var FuelStop = mongoose.model('FuelStop', fuelSchema);
module.exports = FuelStop;
And where I'm attempting a basic model.save operation:
app.post('/', function (req, res ) {
results = req.body;
var fuelStop = new FuelStop (results)
fuelStop.save(function() {
console.log('record saved to monogoDB');
});
})
Any clue as to why my 'fuelTracker' database doesn't appear in the command line when I run 'show databases' within mongo?
THANK YOU!!
did you try show dbs? show databases print all databases available, see the doc here: https://docs.mongodb.com/manual/reference/mongo-shell/
The database doesn't get created until you insert data into a collection in the database.
I tested your code by creating and running a script to seed the fuelTracker database with example JSON data. I then ran show databases and was able to see fuelTracker listed.
If you would like to try this, in a new file seed.js:
const db = require('./fileName.js');
const fs = require('fs');
let fuelData = fs.readFileSync('./data.json', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
let jsonFuel = JSON.parse(fuelData);
db.remove({}, () => {
console.log('Successfully removed fuel data');
db.collection.insert(jsonFuel, (err, docs) => {
if (err) {
console.log(`error inserting data: ${err}`);
} else {
console.log(`Fuel data was stored: ${docs}`);
}
});
});
Then create example data in data.json:
[
{
"time":"04/18/2018",
"miles":"28",
"gallons":"30"
}
]
Then run your seed file and your database should hopefully be showing up.

How to use node-mysql correctly with Express.js?

I'm wondering how to use the module node-mysql correctly in Node.js (using Express.js). I have a main router with this:
var Post = require('./models/post.js');
app.get('/archives', function (req, res) {
Post.findArchives(function(posts, err) {
if(err)
res.send('404 Not found', 404);
else
res.render('archives', { posts: posts});
});
});
And here's the content of the file post.js:
var mysql = require('mysql');
var dbURL = 'mysql://root#localhost/mydatabase';
exports.findArchives = function(callback) {
var connection = mysql.createConnection(dbURL);
connection.query('SELECT * FROM blog_posts_view WHERE status != 0 ORDER BY date DESC', function(err, rows) {
if(err) throw err
callback(rows, err);
connection.end();
});
};
How can I improve it? Improve the error handling? Also, there's the function handleDisconnect(connection); on their Github (https://github.com/felixge/node-mysql) that I'm not really sure how to integrate to make sure that the application will not crash when the database is not responding.
Thanks!
Take a look at the mysql-simple library. It combines node-mysql with a pooling library to create a connection pool, and also includes the code to handle the disconnects.
If you want to make it super easy, you could just use that module.

How to push out requested data from mongodb in node.js

I'm working with Node.js, express, mongodb, and got stuck on this data passing between frontend and backend.
Note: code below is middleware code for front- and backend communication
Here I successfully get the input value from the frontend by using req.body.nr
exports.find_user_post = function(req, res) {
member = new memberModel();
member.desc = req.body.nr;
console.log(req.body.nr);
member.save(function (err) {
res.render('user.jade', );
});
};
Here is the problem, I need to use the input value I got to find the correct data from my database(mongodb in the backend) and push out to the frontend.
My data structure {desc : ''}, the desc is correspond to the input value so it should look something like this {desc: req.body.nr} which is probably incorrect code here?
exports.user = function(req, res){
memberModel.find({desc: req.body.nr}, function(err, docs){
res.render('user.jade', { members: docs });
});
};
Would love to have some help.
Thanks, in advance!
Have a look at this great tutorial from howtonode.org.
Because as you can see he uses a prototype and a function callback:
in articleprovider-mongodb.js
ArticleProvider.prototype.findAll = function(callback) {
this.getCollection(function(error, article_collection) {
if( error ) callback(error)
else {
article_collection.find().toArray(function(error, results) {
if( error ) callback(error)
else callback(null, results)
});
}
});
};
exports.ArticleProvider = ArticleProvider;
in app.js
app.get('/', function(req, res){
articleProvider.findAll( function(error,docs){
res.render('index.jade', {
locals: {
title: 'Blog',
articles:docs
}
});
})
});
Also make sure you have some error checking from the user input as well as from the anybody sending data to the node.js server.
PS: note that the node, express and mongo driver used in the tutorial are a bit older.

How do I use node-mongodb-native to connect to Heroku?

I'm getting really confused over how to connect to MongoLab on Heroku.
To connect using the uri to Heroku, I was trying to follow this example:
http://experiencecraftsmanship.wordpress.com/2012/01/06/heroku-node-js-mongodb-featuring-the-native-driver/
I looked at both his web.js and deep.js.
They both do something like:
connect.createServer(
require( 'connect-jsonrpc' )( contacts )
).listen( port );
But then only the database query in 'contacts' get passed into this server then?
Am I allowed to do multiple connect.createServer for each of my database access method?
The following is part of my code when just connecting to MongoDB locally. I am unsure of how to modify it to connect to MongoLab on Heroku.
Can someone teach me how to modify my code to connect? Or explain some of these concepts? I have no idea why the author of that website I posted used so many callbacks to do a database call, when my approach below seems straightforward enough (I'm new to JavaScript, not good with callbacks).
var app = module.exports = express.createServer(
form({ keepExtensions: true })
);
var Db = require('mongodb').Db;
var Server = require('mongodb').Server;
var client = new Db('blog', new Server('127.0.0.1', 27017, {}));
var posts;
var getAllPosts = function(err, collection) {
collection.find().toArray(function(err, results) {
posts = results;
console.log(results);
client.close();
});
}
app.get('/', function(req, response) {
client.open(function(err, pClient) {
client.collection('posts', getAllPosts);
});
// some code
response.render('layout', { posts: posts, title: 'Raymond', contentPage: 'blog' });
});
You connect to your mongolab database (so you can't create a new "blog" database). process.env.MONGOLAB_URI includes the database name as well. See your mongolab uri:
heroku config | grep MONGOLAB_URI
It looks like: mongodb://heroku_app123456:password#dbh73.mongolab.com:27737/heroku_app123456
On github there is an example how to connect and retrieve data from a mongolab database.
Use "connect" to connect to mongo, instead of defining db, server, client:
var connect = require('connect');
var mongo = require('mongodb');
var database = null;
var mongostr = [YOUR MONGOLAB_URI];
mongo.connect(mongostr, {}, function(error, db)
{
console.log("connected, db: " + db);
database = db;
database.addListener("error", function(error){
console.log("Error connecting to MongoLab");
});
});

Categories