i'm having a problem with a select statement.
It looks like:
myda = new SqlDataAdapter("Select * FROM tblAgenda WHERE tAgUsrId ='" + Session["usrId"] + "' AND tAgTBD = '" + Session["username"] + "' OR tAgTBD = '" + DBNull.Value + "' ", myconn);
But I have no idea how to make that DBNull.Value work. I also tried with just using "" instead, but it also doesn't work.
Any ideas on how to rewrite this statement please? Thank you.
Assuming that your session values have already been sanitised, then you can do the following:
myda = new SqlDataAdapter("Select * FROM tblAgenda WHERE tAgUsrId ='" +
Session["usrId"] + "' AND tAgTBD = '" +
Session["username"] + "' OR tAgTBD is null", myconn);
The above assumes that you want all rows where tAgTBD are null. If you want to keep the restriction the to the user ID, you'll want to add brackets around the two ORed conditions:
myda = new SqlDataAdapter("Select * FROM tblAgenda WHERE tAgUsrId ='" +
Session["usrId"] + "' AND (tAgTBD = '" +
Session["username"] + "' OR tAgTBD is null)", myconn);
If the session values haven't been sanitised, then you need to read up on SQL injection, and look at using an SqlCommand with parameters instead of constructing a string; although you may prefer to go this route anyway - it's a better habit to acquire, long term, and then you don't need to consider whether the values have been sanitised.
Related
Im trying to avoid using native query. I have this query that uses the filter function, how could I rewrite this to not use that and work in regular jpql?
#Query(
"SELECT time_bucket(make_interval(:intervalType), d.time) as groupedDate, " +
"CAST(d.team_Id as varchar) as teamId, CAST(d.service_Id as varchar) as serviceId, CAST(d.work_id as varchar) as workId, " +
"ROUND(CAST(count(d.value) filter ( where d.type = 'A') AS numeric) /" +
" (CAST(count(d.value) filter ( where d.type = 'B') AS numeric)), 4) as total " +
"FROM datapoint d " +
"WHERE d.team_Id = :teamId and d.service_id in :serviceIds and d.work_id = :workspaceId and d.type in ('A', 'B') " +
"AND d.time > :startDate " +
"GROUP BY groupedDate, d.team_Id, d.service_Id, d.workspace_Id " +
"ORDER BY groupedDate DESC",
nativeQuery = true
)
in the FROM statement you have to use the DAO object instead of the table name
I have viewed some of the related question but the solutions on them are bit older. Most of them are using EntityManager. I have written the following native query in JpaRepository and when I get geojson as a String I'm getting the error mentioned in the title.
Here is my query
#Query(value = "SELECT\n"
+ " json_build_object(\n"
+ " 'type', 'FeatureCollection',\n"
+ " 'features', json_agg(\n"
+ " json_build_object(\n"
+ " 'type', 'Feature',\n"
+ " 'geometry', ST_AsGeoJSON(a.check_in_geom)\\:\\:json,\n"
+ " 'properties', json_build_object(\n"
+ " 'username', a.username,\n"
+ " 'users', (\n"
+ " -- Generate json array of \"users\"\n"
+ " SELECT array_to_json(array_agg(u.*)) \n"
+ " FROM users u \n"
+ " WHERE u.username = a.username\n"
+ " GROUP BY u.username\n"
+ " )\n"
+ " )\n"
+ " )\n"
+ " )\n"
+ " ) Json\n"
+ "FROM\n"
+ " attendances a, users u\n"
+ " WHERE a.username = u.username AND u.designation = 'Manager' AND date_trunc('day', a.created_at)\\:\\:DATE = '2022-04-04'"
+ " ;", nativeQuery = true)
String getAttendanceGeoJsonByDesignationAndDate(String designation, String dateStr);
For now I'm passing designation and date as static values.
When I run this query on Postgresql it runs successfully and return the expected geojson. But spring boot does not allow the result to be as String or it throws exception while running the query.
Please let me know how can I fix it. Also if I need to provide more detail, do let me know.
We are using EF Core to make database call and we have a MERGE call to conditionally insert a record and what we want is once the record is inserted we want to get that new RECORD in the OUTPUT (along with the identify column). I am doing this avoid additional Select query post the insert. Following is our code, any guidance on how we can get the OUTPUT of the new record along with the identify column (auto generated value):
string query = $"MERGE INTO [ReceiptMaster] AS old " +
$"USING (VALUES ({receipt.ProfileID},'{receipt.TranscribeID}','{receipt.ReceiptStatusID}'," +
$"'{receipt.ReceiptTypeID}','{receipt.TransactionDate}','{receipt.ProcessTypeID}'," +
$"'{receipt.TripTranscriptionVendorID}','{receipt.AcquireTypeID}',{receipt.CategoryTypeID}," +
$"'{receipt.IsResubmitted}','{receipt.IsResubmittedByPanel}', {receipt.ScrapeJobID}, " +
$"'{receipt.TripTranscriptionPayloadID}')) " +
$"AS new (ProfileID, TranscribeID, ReceiptStatusID, ReceiptTypeID, TransactionDate, ProcessTypeID, " +
$"TripTranscriptionVendorID, AcquireTypeID, CategoryTypeID, IsResubmitted, IsResubmittedByPanel, " +
$"ScrapeJobID, TripTranscriptionPayloadID) " +
$"ON new.TranscribeID = old.TranscribeID " +
$"WHEN NOT MATCHED BY TARGET THEN INSERT (ProfileID, TranscribeID, ReceiptStatusID, ReceiptTypeID, " +
$"TransactionDate, ProcessTypeID, TripTranscriptionVendorID, AcquireTypeID, CategoryTypeID, IsResubmitted, " +
$"IsResubmittedByPanel, ScrapeJobID, TripTranscriptionPayloadID) VALUES (ProfileID, TranscribeID, ReceiptStatusID, " +
$"ReceiptTypeID, TransactionDate, ProcessTypeID, TripTranscriptionVendorID, AcquireTypeID, CategoryTypeID, " +
$"IsResubmitted, IsResubmittedByPanel, ScrapeJobID, TripTranscriptionPayloadID);";
var context = _dbContext.Database.ExecuteSqlRaw(query);
if (context == 0) return false;
else return true;
}
I have done that before, but in this case I have an insert into table query where value of the column of the target table comes as a result from another query. Having that, I'm not sure if my parametarized query is formatted the right way.
Here is an original query without before Sql Injection fix:
cmd.CommandText += "insert into controlnumber (controlnumber, errorid)
values ('" + ControlNumber + "', (select errorid from error where
errordescription = '" + ErrorDescription + "' and errortype = '" +
ErrorType + "' + and applicationid = " + ApplicationID + " and statusid =
" + StatusID + " and userid = " + UserID + " and errortime = '" +
ErrorTime + "');";
This is the query after I tried to fix Sql Injection:
cmd.CommandText = "insert into ControlTable(ControlNumber, ErrorID)
values (#ControlNum, (select errorid from error where errordescription =
#ErrorDescription and errortype = #errorType and applicationid =
#ApplicationID and statusid = #StatusID and userid = #UserID and
errortime = #ErrorTime)"
This is where I add parameters:
.....
command.CommandType = CommandType.Text
command.Parameters.AddWithValue("#ErrorDescription ", ErrorDesc);
command.Parameters.AddWithValue("#ControlNum", cntNumber);
command.Parameters.AddWithValue("#errorType",ErrorType);
command.Parameters.AddWithValue("#ApplicationID",AppID);
command.Parameters.AddWithValue("#StatusID",StatusID);
command.Parameters.AddWithValue("#UserID",UserID);
....
I'm just wondering if my CommandText is formatted the right way.
Thank's
try this:
cmd.CommandText = "insert into ControlTable(ControlNumber, ErrorID)
select #ControlNum, errorid from error where errordescription =
#ErrorDescription and errortype = #errorType and applicationid =
#ApplicationID and statusid = #StatusID and userid = #UserID and
errortime = #ErrorTime)"
When using INSERT INTO SELECT FROM, you do not use keyword VALUES. The syntax is:
INSERT INTO TABLE(columns) SELECT ... FROM TABLE2
String query="select book_code, book_name, student_name, class, roll_no, issue_date, return_date from lib where" + s1 + "" + s2 + "" + s3 + ";" ;
ResultSet rs=stmt.executeQuery(query);
This is the code where s1,s2 are combo boxes from which the search field and operator is being selected and s3 is the search criteria.
Where am I wrong?
I think your mistake might be that you are missing a space when concatenating your query like this.
where" + s1 + "" + s2 + "" + s3 + ";"
(there is no space after the where keyword)
If you are using string you have to include that in single quotes.
String query="select book_code, book_name, student_name, class, roll_no, issue_date, return_date from lib where " + s1 + "" + s2 + "'" + s3 + "'";
So use the query in if condition according to the type that you choose.