I have a servlet called DBChart mapped to url /db.the servlet outputs some data based on the sql query used here.
What I have:
At client end, I am making an ajax call like this:
$.ajax({
type : 'POST',
async: false,
url : 'http://localhost:8080/DBCHART/db',
success : function(data) {/*some code*/})
and At server end, a static query that says:
String sql ="select * from Employee"
What I want:
I want to be able to pass some parameters here like :
url: http://localhost:8080/DBCHART/db?Name = 'xyz'?Age = 21
and at server end, the query in this case should become:
select * from Employee where Name ='xyz' and Age = 21
i.e only if those parameters were supllied otherwise it should stay
select * from Employee
Can I please get some direction to create dynamic sql for this efficiently?
let's say in this case you're using varName as 'xyz' and varAge as 21
-- -- Name = 'xyz'?Age = 21
you can use some logic like this (point to ponder: WHERE 1 = 1 )
string sqlQuery = " select * from Employee where 1 = 1 ";
if(null != varName && !varName.isEmpty())){
// add criteria for Name
sqlQuery += " AND Name = '"+ varName + "'"; // TODO: use parametrized query
}
if(null != varAge && varAge > 0){
// add criteria for Age
sqlQuery += " AND Age = "+ varAge ; // TODO: use parametrized query
}
Related
I have a SQL query to return customer's transaction header using customer's card_number. The SQL query will return a column called audit_number. The problem is the when i execute the SQL query using SSMS software, the query returns proper results, but when i execute the query on my Node JS script some of the audit_number are wrong.
The audit_number should be 14111990000015953 and 14111990000015952 but when i execute the query in my NODE JS script both audit_number become 14111990000015952.
Here is my sql query
SELECT
h.Log_trxdate AS trx_date,
CAST(h.log_audit AS varchar) AS audit_number,
h.currency_code
FROM log_header h
WHERE h.id_code = '10000010055919' --card_number
Here is my Node JS Script
var querySQL = " SELECT ";
querySQL = querySQL + " h.Log_trxdate AS trx_date, ";
querySQL = querySQL + " CAST(h.log_audit AS varchar) AS audit_number, ";
querySQL = querySQL + " FROM log_header h ";
querySQL = querySQL + " WHERE h.id_code = 10000010055919 ";
sql.connect(config, function (err) {
var req = new sql.Request();
req.query(querySQL, function (err, result) {
console.log(result);
});
});
You need to change your datatype number to varchar/text since in javascript if the number length is more than 16 digits then it will give you some random number.
So to get exact result you should change your Datatype from number to string.
For example if you check number
Number(1111111111111111)//16 digits
Result is 1111111111111111
But if you put Number(11111111111111111)//17 digits
then result will be 11111111111111112 something
I want to build a SELECT statement using a list of conditions that come from the query string of a REST api. I wrote this function, but maybe it is vulnerable to SQL injection. Can someone tell me if this is vulnerable how to fix it? Perhaps I should use some kind of SQLBuilder package? or is there a way to do it with just dotNet. I'm using dotNet 4.6.1
string BuildSelect(NameValueCollection query)
{
var result = "SELECT * FROM MYTABLE";
if (query.Count == 0) return result;
var logic = " WHERE ";
foreach (string key in query)
foreach (string v in query.GetValues(key))
{
result += logic + key + " = " + v;
logic = " AND ";
}
return result;
}
Yes it is vulnerable to SQL injection attack. You could build your query to use parameters instead (you are simply using an = check only).
Since you know the tablename, that means you also know what the columns (keys) can be. Thus, you could loop your columns, if the collection has that key then add it to the where as a parameterized statement BUT value part is NOT passed as a string, you parse it to the type it should be (or let the backend do the conversion and get error if cannot be converted). In pseudocode:
List<string> clauses = new List<string>();
var result = "SELECT * FROM MYTABLE";
foreach( var col in myTable.Columns )
{
if (query.ContainsKey(col.Name))
{
clauses.Add( $"{col.Name} = #{col.Name}";
string v = query[col.Name];
command.Parameters.Add( $"#{col.Name}", col.Type).Value = typeParse(v);
}
}
if (clauses.Any())
{
result += " WHERE " + string.Join( " AND ", clauses );
}
return result;
HTH
I want do below query in Entity Framework
select
cast(p_min as varchar) + '' + cast(p_max as varchar)
from
user_behave_fact
where
beef_dairy_stat = 'True' and param_id = 2
group by
p_min,p_max
go
Since you have not mentioned a language, I am writing code in C#.
Try this:
using (var dbContext = new DatabaseContext())
{
var output = (
from fact in dbContext.user_behave_facts
where fact.beef_dairy_stat == "True" && fact.param_id == 2
group fact by new {fact.p_min, fact.p_max} in grp
select new
{
ColName = grp.Key.p_min.ToString() + " " + grp.Key.p_max.ToString()
}
).ToList();
}
.ToList() can be changed according to your expectations
I have a static string with parameters, being sent to an SQL Execute command.
The strings have the format of delete 'Name' from table where x = 1 and y = 2 or select * from table where x = 1 and y = 2.
My problem is that I need to break the string into parameters.
How do I break the strings so that I can pass the command with the parameters to a single functional with the least possible work?
I have only one function to fix and handle this problem.
From this:
protected object ExecuteScaler(string queryString)
{ OpenConnection(); }
DbCommand command = _provider.CreateCommand();
command.Connection = _connection; command.CommandText = queryString; command.CommandType = CommandType.Text; if (_useTransaction) {
command.Transaction = _transaction; }
try { returnValue = command.ExecuteScalar(); } ...
Can someone please give me an example?
When you build a sql-command like this:
// don't do this because of sql injection
sql = "SELECT * FROM MyTable WHERE Col2 = " + somevalue;
Where you "break out of" the string constant to place a value, that is the point where you want to use a parameter placeholder:
// safe from sql injection
sql = "SELECT * FROM MyTable WHERE Col2 = #somevalue";
And then you can supply the value for #somevalue using the Parameters collection.
When the query needs some fixed values, then it is probably OK to keep them in the string:
// the "type" never changes for this query:
sql = "SELECT * FROM MyTable WHERE type=1 and Col2 = #somevalue";
I want to perform the following query using Dapper, which currently doesn't return expected results (I think it must be treating the #pName param as literal text within the single quotes?):
var q = "SELECT * FROM Users WHERE Name LIKE '#pName%'";
#pName is the param I assign a value to upon executing the query.
Things work if I just build the SQL like:
var q = "SELECT * FROM Users WHERE Name LIKE '" + name + "%'";
.. but I would prefer to use a param if possible.
I am executing the query using the following code:
o = _cn.Query<User>(q, new { pName = new DbString { Value = name, IsFixedLength = false, Length = 25, IsAnsi = true } }).ToList();
How do I got about this using Dapper?
SELECT * FROM Users WHERE Name LIKE #pName + '%'
I would like to add here another possible solution:
var results = cn.Query("SELECT * FROM Table WHERE Column LIKE #value", new { value = value + "%" });
The wildcard is inside the string var itself, and then we reference that var in the SQL. Applies to any wildcard pattern you want.