I am looking forward to know how can I run an Azure SQL stored procedure with multiple input parameters from Nodejs.
For example, if I have a stored procedure FIND_USERS(activity_status, color, gender) which runs a query
select * from users where isActive = activity_status and bay_color = color and userGender = gender;
I should be able to call this stored procedure from nodejs with the input parameters. The thing to understand here is that I want have a SQL transaction service that can take any CALL PROCEDURE type command along with the set of input parameters and call the procedure using those input parameters irrespective of the number of input parameters.
What I know is that for MySQL, there is a mysql library which lets me run procedures with multiple parameters. I have encapsulated it in MySQLConnector.js service as
var mysql = require('mysql');
exports.query = function(sql, values, next) {
if (arguments.length === 2) {
next = values;
values = null;
}
var connection = mysql.createConnection({
host:host,
user:user,
password:password,
database:database
});
connection.connect(function(err) {
if (err !== null) {
console.log("[MYSQL] Error connecting to mysql:" + err+'\n');
console.log(err == 'Error: ER_CON_COUNT_ERROR: Too many connections')
if(err == 'Error: ER_CON_COUNT_ERROR: Too many connections'){
connection.end();
}
}
});
connection.query(sql, values, function(err) {
connection.end();
if (err) {
throw err;
}
next.apply(this, arguments);
});
}
With this, I can call a stored procedure from nodejs with a function like
MySQLConnector.query('CALL FIND_USERS (?, ?, ?)', [1, 'blue', 'female'], function(err, userData) {
//do something with userData
});
How is it possible to do this for Azure MS SQL?
You can use tedious driver to connect to SQL Server. It supports both input+output parameter for statements and SPs, you can find the example in http://tediousjs.github.io/tedious/parameters.html
Feels free to raise an issue in GitHub if you need more assistance.
Make use of Edje.js and you should create a function and send the parameters when you call the function.
getHorarioFarmacia({pSede:'Sucursal Parrita'}, function (error, result){....
}
For more details, read the comments made by Luis Diego Pizarro here.
Related
I'm discovering Express by creating a simple CRUD without ORM.
Issue is, I'm not able to find any record through the Model.findBy() function
model User {
static async findBy(payload) {
try {
let attr = Object.keys(payload)[0]
let value = Object.values(payload)[0]
let user = await pool.query(
`SELECT * from users WHERE $1::text = $2::text LIMIT 1;`,
[attr, value]
);
return user.rows; // empty :-(
} catch (err) {
throw err
}
}
}
User.findBy({ email: 'foo#bar.baz' }).then(console.log);
User.findBy({ name: 'Foo' }).then(console.log);
I've no issue using psql if I surround $2::text by single quote ' like:
SELECT * FROM users WHERE email = 'foo#bar.baz' LIMIT 1;
Though that's not possible inside parametrized queries. I've tried stuff like '($2::text)' (and escaped variations), but that looks far from what the documentation recommends.
I must be missing something. Is the emptiness of user.rows related to the way I fetch attr & value ? Or maybe, is some kind of escape required when passing string parameters ?
"Answer":
As stated in the comment section, issue isn't related to string escape, but to dynamic column names.
Column names are not identifiers, and therefore cannot be dynamically set using a query parameter.
See: https://stackoverflow.com/a/50813577/11509906
I'm trying to create login page using react front-end and ASP .NET core Back-end.
SO while a user login to the system I have to use the query like
Select * from UserLogin where email="asbhf#gmail.com"
so that my API URL should be
https://localhost:44383/api/UserLogins?email="asbhf#gmail.com"
So that, I tried this code in my UserLoginController.cs
// GET: api/UserLogins?email="asd#gmail.com"
public async Task<IActionResult> GetUserLogin([FromRoute] string email)
{
if (email == null)
{
return NotFound();
}
string query = "SELECT * FROM UserLogin WHERE email = #email";
var UserLogin = await _context.UserLogin
.FromSql(query, email)
.Include(d => d.Username)
.AsNoTracking()
.FirstOrDefaultAsync();
if (UserLogin == null)
{
return NotFound();
}
return Ok(UserLogin);
}
but, It won't print any out put as I expect. Could you please give me any hint to solve my issue.
Firstly , The Include method specifies the related objects to include in the query results. It can be used to retrieve some information from the database and also want to include related entities , not specify the fields to return. For more details , you could refer to here.
Secondly , there are some errors in your data query section , try the following modification:
string query = $"SELECT Username FROM UserLogin WHERE email = #email";
var p1 = new SqlParameter("#email", email);
var UserLogin = await _context.UserLogin
.FromSql(query, p1)
.AsNoTracking()
.FirstOrDefaultAsync();
You could take a look at Executing Raw SQL Queries for the usage of FromSql.
I refer write sql query for entityframework
So my working code is
var UserLogin = _context.UserLogin.Where(c => c.Email == email);
I am trying to make a search bar which works with multiple words, but I am worried about SQL injection.
I am using node express with the npm mssql package.
Here's the code which gets the criteria, generates the SQL and runs it:
router
.get('/search/:criteria', function (req, res) {
var criteria = req.params.criteria;
var words = criteria.split(" ");
var x = ""
words.map(word => x += `name like '%${word}%' and `);
x = x.substring(0, x.length - 5); // Remove trailing 'and'
var query = `SELECT * FROM table WHERE ${x}`
new sql.ConnectionPool(db).connect().then(pool => {
return pool.request().query(query)
}).then(result => {
})
});
A search for something to search would result in this query:
SELECT * FROM table
WHERE
name like '%something%'
and name like '%to%'
and name like '%search%'
I tried some SQL injections myself, but none of them seem to work.
Note: I am aware that we should always use inputs for this. It works fine for one word, but I don't know how to use inputs for many words. Ex:
new sql.ConnectionPool(db).connect().then(pool => {
return pool.request()
.input('input', '%'+criteria+'%')
.query(query)
})
The answer is: It's not safe. Your code does exactly nothing to make it safe, either. Don't build SQL by concatenating/interpolating user-supplied data into the statement.
In addition, you don't do any escaping for LIKE itself, either, so that is just as unclean.
If you need dynamic SQL, build a prepared SQL statement with the expected number of placeholders and then bind user-supplied values to those placeholders.
router.get('/search/:criteria', (req, res) => {
const ps = new sql.PreparedStatement();
const sqlConditions = [];
const escapedValues = {};
// set up escaped values, safe SQL bits, PS parameters
req.params.criteria.split(" ").forEach((v, i) => {
const paramName = 'val' + i;
escapedValues[paramName] = v.replace(/[\\%_]/g, '\\$&');
sqlConditions.push(`name LIKE '%' + #${paramName} + '%' ESCAPE '\'`);
ps.input(paramName, sql.VarChar);
});
// build safe SQL string, prepare statement
const sql = 'SELECT * FROM table WHERE ' + sqlConditions.join(' AND ');
ps.prepare(sql);
// connect, execute, return
ps.execute(escapedValues).then(result => {
res(result)
});
});
(Disclaimer: code is untested, as I have no SQL Server available right now, but you get the idea.)
Hello everyone i am trying to run a query as follows, but i always get "SQL ERROR: undefined"
What am i doing wrong.
db = window.openDatabase("Database", "1.0", "SQLDB", 200000);
RunQuery ("DROP TABLE IF EXISTS ARTIGOS");
function RunQuery(QueryExecute) {
db.transaction(function(transaction){
transaction.executeSql(QueryExecute,successCB,errorCB);
})
}
function errorCB(err) {
alert("SQL Error: "+err.message);
}
function successCB() {
alert("SQL OK");
}
One possibility is that the transaction.executeSql method takes a parameters array as its second argument. So to use the callbacks like you have, you may have to pass in an empty array for the parameters. e.g.:
transaction.executeSql(QueryExecute, [], successCB, errorCB);
Referenced from the Cordova docs here:
https://cordova.apache.org/docs/en/latest/cordova/storage/storage.html
I am able to successfully create adapter for creation and insertion in sql but updation i have doubt below is my code where i want to update a certain field values based on wrkname and i am getting in or out error.
var updateStatement = WL.Server.createSQLStatement("UPDATE office1 SET wrkid=?, wrkname=?, empref=? WHERE wrkname=?");
function updateoffice(wrkid,wrkname,empref,wrkname) {
return WL.Server.invokeSQLStatement({
preparedStatement : updateStatement,
parameters : [wrkid,wrkname,empref,wrkname]
});
}
Aren't you missing the fourth parameter, wrkname (which you're using twice...)?
For example, this worked well for me:
var update = WL.Server.createSQLStatement("UPDATE users SET stdid=? WHERE userId=?");
function updatevaluesprocedure(stdId,userId) {
return WL.Server.invokeSQLStatement({
preparedStatement : update,
parameters : [stdId,userId]
});
}
Two parameters are expected, two parameters were received.
In your case four parameters are expected...