i am new to node.js and my boss has entrusted me with a job to integrate a notification system in our attendance project..
so far i have successfully created a connection to my data base using express and mysql node modules
and the code that helped me in achieving that is given below
var express=require('express');
var mysql=require('mysql');
var app=express();
var connection=mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'attendance'
});
connection.connect(function(error) {
if(!!error) {
console.log('Error in connection');
} else {
console.log('Connected');
}
});
app.get('/',function (req, resp) {
connection.query("Select * from employee_leaves", function (error, rows, fields) {
if (!!error) {
console.log("Error in the query");
} else {
console.log("successfully done\n");
console.log(rows);
}
});
})
app.listen(1337);
// now the issue is i want to query this statement
SELECT * from employee_leaves WHERE employee_leave_company_name ='$sup_company_name' AND leave_status='Pending'ORDER BY employee_leave_id desc"
the issue is these variable $sup_company_name is in php so
1) how should i fetch value from that variable
2)how to use where clause in node.js
Note:: $sup_company_name is declared in my require.php file
the code of require.php file is given below P.S i m accessing that variable in my other pages by include('require.php') but i dont know how to access that variable in node.js
session_start();
$sup_id = $_SESSION['employee_id'];
$sup_type=$_SESSION['employee_type'];
$sup_company_name=$_SESSION['employee_company_name'];
Related
I'm trying to execute a stored procedure and when I run the code below, the code in the function for the query is not being run at all. There is also no error. I am thinking somehow SQL Server is interpreting the query for the stored procedure incorrectly and stalling because if I use a regular query e.g. select top 1 * from Custom.ExampleTable it works fine.
var express = require('express');
var app = express();
const sql = require("mssql/msnodesqlv8");
// example db connection...
const connectionString = "server=dev\\instance1;database=123456;user=ORG\\NAME;Trusted_Connection=Yes;"
sql.connect(connectionString, err => {
console.log("connected: " + connectionString)
try {
new sql.Request().input('var', sql.VarChar, 2222).execute('dbo.check_ex', (err, results) => {
// code not being run...
console.dir("test")
if (err) {
console.log(err);
}
console.log(rows);
})
} catch (err) {
console.log(err);
}
})
var server = app.listen(5000, function () {
console.log('Server is running..');
});
Output below:
Server is running..
connected: server=dev\\instance1;database=123456;user=ORG\\NAME;Trusted_Connection=Yes;
I'm new in Node JS and I'm trying to display the fetched data from my MySQL Table into a table in my HTML-File. But I couldn't find anything that helped me. I would really appreciate it if somebody can help me to get a solution! :)
Here's my js-code:
//app.js
// Get the mysql service
var mysql = require('mysql');
var express = require('express');
var app = express();
app.get('/', function (request , response) {
fetchData(response);
console.log('Done. Displayed Data.');
});
// Add the credentials to access your database
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'Breunninger',
port: '3306'
});
// connect to mysql
connection.connect(function(err) {
if(err){throw err;}
console.log('Connected');
});
function executeQuery(sql, cb){
connection.query(sql, function( result, fields){
cb(result);
})
}
function fetchData(response){
executeQuery("SELECT username, tor, datum, sendungsstruktur FROM Buchung JOIN user ON(user.id = Buchung.userid)", function (result) {
console.log(result);
response.write('<div class="container-wrap"><table id="example" class="display"><tr>');
for(var column in result[0]){
response.write('<td> <label>' + column + '</label></td>');
response.write('</tr>');
}
for(var row in result){
response.write('<tr>');
for(var column in result[row]){
response.write('<td>' + result[row][column]+ '</td>');
}
response.write('</tr>');
}
response.end('</table></div>');
});
}
<div class="container-wrap">
<div class="flexslider">
<script src="app.js"></script>
</div>
</div>
There's a small (but critical!) error in the executeQuery function, the first argument should be the error object, so if you can re-write this as below your query should work.
function executeQuery(sql, cb){
connection.query(sql, function( error, result, fields){
if (error) {
console.error("An error has occurred:", error);
} else {
cb(result);
}
})
}
Node callback usually reserve the first argument for an error object, it's easy to miss this!
Also, we should be clear, the Node.js Express code will be running on the server side, so to see the results you need to point your browser to the host and port this is serving, e.g. http://localhost:3000/ (if you do:)
app.listen(3000);
I have created an application using Node.js to connect with SQL Server. Below is the code:
app.get('/SalesStatistics', function (req, res) {
var Connection = require('tedious').Connection;
// config for your database
var config = {
user: "****",
password: "*****",
server: "abc",
database: "xyz"
};
var connection = new Connection(config);
connection.on('connect', function (err) {
// If no error, then good to proceed.
console.log("Connected");
executeStatement();
});
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;
function executeStatement() {
request = new Request("select * from employee;", function (err) {
if (err) {
console.log(err);
}
});
var result = "";
request.on('row', function (columns) {
columns.forEach(function (column) {
if (column.value === null) {
console.log('NULL');
} else {
result += column.value + " ";
}
});
console.log(result);
result = "";
});
request.on('done', function (rowCount, more) {
console.log(rowCount + ' rows returned');
});
connection.execSql(request);
}
});
Received the below error in console:
message: 'Requests can only be made in the LoggedIn state, not the Connecting state'
code: EIINVALIDSTATE
Also tried the sample from Github site, but still I could not connect to SQL Server. Please let me know if any other possibility.
I just encountered the same problem awhile ago running the same code above with similar environment.
It turn out that I did not configure the sql server (using Sql Server Management Manager) to accept TCP connection to port (1433). After I done that, everything work fine.
Hi I am currently trying to output mysql data to a browser window instead of the console, and I have not a clue on how to do this in Node, which I am quite new to.
Here is the mysql.js file:
'
var mysql = require ("mysql");
var connection = mysql.createConnection({
host:"localhost",
user: "root",
});
connection.connect(function (err) {console.log( "Successfully Connected.");
if (err) throw err;
});
var query = connection.query("SELECT * FROM myTable", function (err, result, fields){
if (err) throw err;
console.log('result:', result);
});
connection.end();'
You need to create a server which you can connect to and receive data from with a browser. The most convenient and by far the simplest way to do this is HTTP. You can read about HTTP servers in node.js here. The fist code snippet on that page demonstrates a HTTP server with one handler function, which is all you need to achieve your goal.
An (untested) example for convenience:
// Dependencies
var mysql = require("mysql"),
http = require("http");
// This holds our query results
var results;
// Connect to database
var connection = mysql.createConnection({
host: "localhost",
user: "root"
});
connection.connect(function(err) {
if (err) throw err;
console.log("Connected to database");
});
connection.query("SELECT * FROM myTable", function(err, rows, fields) {
if (err) throw err;
results = rows;
connection.end(); // Disconnect from database
});
// Function to handle browser's requests
function requestHandler(req, res) {
res.end(JSON.stringify(results)); // Respond to request with a string
}
// Create a server
var server = http.createServer(requestHandler);
// That magic number 8080 over here is the port our server listens to.
// You can access this webpage by visiting address http://localhost:8080
server.listen(8080, function() {
console.log("Server online");
});
I have a simple file model.js like follows:
var mongo = require('mongodb');
var mongoUri = process.env.MONGOLAB_URI ||
process.env.MONGOHQ_URL ||
'mongodb://localhost/mydb';
exports.connect = mongo.Db.connect(mongoUri, function(err, db) {
console.log("Connect to the database successfully")
});
and in my web.js I load the model using model = require('./model.js'). One werid thing is that although I did not call model.connect(), the message "Connect to the database successfully" still got logged to my console. Why is this happening and is there a way to avoid it?
EDIT:Never mind I have found a workaround:
exports.connect = function(){
mongo.Db.connect(mongoUri, function(err, db) {
console.log("Connect to the database successfully")
});
}
exports.connect = mongo.Db.connect(mongoUri, function(err, db) {
console.log("Connect to the database successfully")
});
You just called mongo.Db.connect() and assigned its result to exports.connect.
That code runs as soon as you require() the module.
Instead, you need to create a function:
exports.connect = function() { ... };