Sql dynamic query syntax error - javascript

This is my sql query
"select * from applicant where email =ABC.Com"
I want table name, colum name and value after where clause dynamic in form of variables there. Can you tell me the right syntax? I have tried this so far
"select * from " tableNameVariable+"where "columnNameVariable+"= "inputedEmailVariable
now this query is giving an error near =inputedEmailVariable.
Note : I want to use this string in nodejs function. Please tell me right syntax?

Try:
"select * from " + tableNameVariable + " where " + columnNameVariable + " = '" + inputedEmailVariable + "'"

You're missing some + operators, and also missing a space before where.
var sql = "select * from " + tableNameVariable + " where " + columnNameVariable + " = " + inputedEmailVariable
You should be very careful if the variables are coming from user input, since this can result in SQL injection. Make sure the variables contain table and column values that they're allowed to access.
And if you're compareing the column with a string, you'll need quotes around the string. But it would be better to use a placeholder at that point, rather than concatenating the variable.

Related

Array in sql statement not working with placeholder ?nodejs

sql query does not accept array as value when it is used in a placeholder, It only returns one result even though result is greater than 1. Not using a placeholder and withouting escaping it works perfectly returns the right amount of results.
//works
SELECT * FROM users WHERE userId IN (" + followerIds.join() + ");";
//does not work
SELECT * FROM users WHERE userId IN (?);";
con.query(queryFollowerstTable, [followeringIsd.join()],function(err,result)..
All I had to do was parse followerIds.join() to an int and It worked.
followerIdsParsed = followerIds.join().split(',').map(Number);
followingIdsParsed = followingIds.join().split(',').map(Number);
var queryFollowerstTable = "SELECT * FROM users WHERE userId IN (?); SELECT *
FROM users WHERE userId IN (?);";
con.query(queryFollowerstTable, [followerIdsParsed, followingIdsParsed],
function(err, result) {..
Change
con.query(queryFollowerstTable, [followeringIds.join()],function(err,result)
to
con.query(queryFollowerstTable, followeringIds.join(),function(err,result)
In your original example:
SELECT * FROM users WHERE userId IN (" + followerIds.join() + ");";
You are passing in a string not an array

JS: how to filter table using variable

I have a function that I need to use for filtering table rows:
setFilterString("Filter");
But I have a problem. I can set it to
setFilterString("OrderID = 5");
and it will filter out row where OrderID is equal to 5 but if i try using a variable that has a value taken before like this
setFilterString("OrderID = vOrderID");
I get error "Invalid column name 'vOrderID'." (as vOrderID is variable and not a column, I guess)
I have seen somewhere in filter section inputting something like this ("OrderID = '" & vOrderID & "'") but it doesn't have any result at all for me. Doesn't even throw any error in the console.
JavaScript assumes you are just passing a string to the function. If you want to use the variable, you should try this:
setFilterString("OrderID = '" + vOrderID + "'"); // Results in OrderID = '5'
or
setFilterString("OrderID = " + vOrderID); // Results in OrderID = 5
depending on the body of your function.
Use + instead of &: setFilterString("OrderID = " + vOrderID) should work.
Use "+" for merge strings:
setFilterString("OrderID = " + vOrderID)
You can also try to use ${idvOrderID} inside string:
setFilterString("OrderID = ${vOrderID}")
Or:
setFilterString(sprintf("OrderID = %s", vOrderID))
Remember about difference between ' and "

Passing sort order as a parameter

Referring to the sample SQL statement below. I'm able to pass parameter values to the placeholder '?' in the statement. However I'm wondering whether it is possible to pass in the sort order in the same way?
So instead of this:
//Create SQL query
var getAccountsTransactionsStatement = WL.Server.createSQLStatement(
"SELECT transactionId, fromAccount, toAccount, transactionDate, transactionAmount, transactionType " +
"FROM accounttransactions " +
"WHERE accounttransactions.fromAccount = ? OR accounttransactions.toAccount = ? " +
"ORDER BY transactionDate DESC " +
"LIMIT 20;"
);
Can I have this:
//Create SQL query
var getAccountsTransactionsStatement = WL.Server.createSQLStatement(
"SELECT transactionId, fromAccount, toAccount, transactionDate, transactionAmount, transactionType " +
"FROM accounttransactions " +
"WHERE accounttransactions.fromAccount = ? OR accounttransactions.toAccount = ? " +
"ORDER BY ? DESC " +
"LIMIT 20;"
);
And to invoke it:
//Invoke prepared SQL query and return invocation result
function getAccountTransactions1(accountId){
return WL.Server.invokeSQLStatement({
preparedStatement : getAccountsTransactionsStatement,
parameters : [accountId, accountId, transactionDate]
});
}
Two things:
This query piece:
WHERE accounttransactions.fromAccount = ? OR accounttransactions.toAccount = ?
Could be replaced with this:
WHERE ? in (accounttransactions.fromAccount, accounttransactions.toAccount)
No you can't. Parameters are values - kind of static stuff - while column names are not. You could probably work around the issue somehow in limited way by using s.t. like this:
ORDER BY
CASE ?
WHEN 'transactionDate' THEN transactionDate
WHEN 'someotherdate' THEN someotherdate
ELSE DATE '2010-01-01'
END
Note however that's a messy construction. Also depending on the type of the database you're using you might want to cast all the columns into one data type i.e. string. so to_char(transactionDate,'yyyy-mm-dd hh24:mm:ss') might be in order but you need to ensure that the sorting is proper in your case (as number tend to mess stuff up like '2' > '13').

NodeJS + PostgreSQL: INSERT has more target columns than expressions

I'd like to INSERT the current timestamp with CURRENT_TIMESTAMPon each new user registration. The column number equal the number of parameters in VALUES. Yet I get INSERT has more target columns than expressions. Using the node-postgres npm module as a controller.
//Just 3 parameters, timestamp is hardcoded in the query
exports.create = function (username, email, password) {
DB.connect(connection, function (err, client, done) {
var query = client.query(
//4 columns
"INSERT INTO users (username, email, userpass, datecreated) VALUES" +
//4 parameters
"(" + "'" + username + "'" + "," + "'" + email + "'" + "," + "'" + password + "'" + "'CURRENT_TIMESTAMP')");
query.on('error', function (error) {
console.log("query returned an " + error);
});
query.on('row', function (row, result) {
result.addRow(row);
});
});
};
Missing comma after password and no tics around current_Timestamp
"INSERT INTO users (username, email, userpass, datecreated) VALUES" +
//4 parameters
"(" + "'" + username + "'" + "," + "'" + email + "'" + "," + "'" + password + "," + "'CURRENT_TIMESTAMP)"
--- While this may have been the accepted answer addressing the immediate issue, I highly recommend Craig and Lars answers be evaluated. Use of Parameters is a far better long term approach as it is more secure; actually easier to code once you understand how, and the correct modern paradigm.
My previous answer was based on older provided code, it isn't accurate anymore so I removed it.
You're missing a comma , between password and CURRENT_TIMESTAMP.
I'd advise you to use parameterized queries instead of building them yourself like this.
`"(" + "'" + username + "'" + "," + "'" + email + "'" + "," + "'" + password + "'" + "'CURRENT_TIMESTAMP')"`
Nonononono!
That is not how you pass parameters, and may bewhy you're having problems. (xQbert points out you're also missing a comma).
Imagine if I entered the username
');--DROP TABLE users;--
Splat. There goes your application.
Use parameterized queries by binding parameters to placeholders. This is often called "prepared statements" though they're really something different.
e.g.
client.query(
"INSERT INTO users (username, email, userpass, datecreated) VALUES ($1, $2, $3, current_timestamp)",
[username, email, password])
Your problem will go away.
Now read this.
Note that this isn't just a security problem, it's also a bug that will cause errors even from non-malicious users. I enter a nice secure looking password like 94/Ql#$'B'wC. Boom, your app falls over with a database error.

Mysql + ASP how to add a record

My asp (and js) code works good but i don't know the exact command to INSERT a record into a DB. I'm able to "read", "update" and "delete" from db, but not insert!
(db server values are example)
var Cn = new ActiveXObject("ADODB.Connection");
Cn.Open("server=1.1.1.1;db=dbserver; DRIVER={MySQL ODBC 3.51 Driver};uid=login;pwd=password");
var value1 = new String(Request.Form("value1"));
var value1 = new String(Request.Form("value1"));
var value1 = new String(Request.Form("value1"));
Cn.Execte("INSERT INTO table (col1,col2,col3) VALUES (value1,value2,value3)");
Cn.Close();
Response.Redirect("home.asp");
Can someone help me?
thanks!
You will have concatenate the values into the sql string like :
Cn.Execute("INSERT INTO table (col1,col2,col3) VALUES ('" + value1 + "','" + value2 + "','" + value3 + "')");
The ' are used assuming the columns in the db are strings, otherwise you don't need it.
If value paramaters are string - nvarchar, text etc.
You must enclose them into quotes. Your statement must look like this.
Cn.Execute("INSERT INTO table (col1,col2,col3) VALUES (value1,'" + value2 + "','" + value3 + "')");
I assumed col2 and col3 are string types and col1 isn't.

Categories