JPA named query | Could not extract resultset - database

I am newbie in JPA tech stack. I am facing problem in implementing single JPA native query for update and select.
#Modifying(clearAutomatically = true)
#Query(value = "UPDATE stories s "
+ "SET rank = :reorderPosition"
+ " WHERE id = :selectedStory ;"
+ "UPDATE stories s "
+ "SET rank = rank+1"
+ " WHERE rank >= :reorderPosition "
+ "AND id <> :selectedStory ;"
+"SELECT id " +
"FROM stories s " +
"WHERE s.epic_Id = :epicId " +
"ORDER BY rank", nativeQuery = true)
List<Integer> reorder(#Param("selectedStory") int selectedStory, #Param("reorderPosition") int reorderPosition,#Param("epicId") int epicId);
This is giving error "Could not extract resultset"
If I break my query into two parts , its working perfectly.
#Modifying(clearAutomatically = true)
#Query(value = "UPDATE stories s "
+ "SET rank = :reorderPosition"
+ " WHERE id = :selectedStory ;"
+ "UPDATE stories s "
+ "SET rank = rank+1"
+ " WHERE rank >= :reorderPosition "
+ "AND id <> :selectedStory ;"
, nativeQuery = true)
void reorder(#Param("selectedStory") int selectedStory, #Param("reorderPosition") int reorderPosition);
#Query(value =
"SELECT id " +
"FROM Story s " +
"WHERE s.epicId = :epicId " +
"ORDER BY rank")
List<Integer> getStoriesIDBySortOrder(#Param("epicId") int epicId);
Please suggest how can I implement in single query and also please refer some good websites to study JPA named query.

Related

TableAPI SQL left join error "doesn't support consuming update and delete changes which is produced by node Join(joinType=[LeftOuterJoin]..."

Need to left join 2 data streams and the Table API throws an exception during starting the Flink app.
It is needed to calculate based on 2 different windows on a same input stream. So eventually the 2 calculated tables/steams need to be joined.
If I use "join" instead of using "left join" the start-up error disappears. Any idea how I can solve it? Is "left join" not supported?
Below is the exception:
org.apache.flink.client.program.ProgramInvocationException: The main method caused an error: Table sink 'default_catalog.default_database.Unregistered_DataStream_Sink_1' doesn't support consuming update and delete changes which is produced by node Join(joinType=[LeftOuterJoin], where=[((userId = userId0) AND (eventEpoch = eventEpoch0))], select=[userId, eventEpoch, AVG_VALUE_A, FIRST_VALUE_B, LAST_VALUE_B, FIRST_EVENTTIME, LAST_EVENTTIME, userId0, eventEpoch0], leftInputSpec=[NoUniqueKey], rightInputSpec=[NoUniqueKey])\n\tat org.apache.flink.client.program.PackagedProgram.callMainMethod(PackagedProgram.java:372)\n\tat org.apache.flink.client.program.PackagedProgram.invokeInteractiveModeForExecution(PackagedProgram.java:222)\n\tat
Below is the code snippet.
Table inputTable = tableEnv.fromDataStream(
inputStream,
Schema.newBuilder()
.columnByExpression("rowtime", "CAST(eventTime AS TIMESTAMP(3))")
.watermark("rowtime", "rowtime - INTERVAL '" + WATERMARK_DELAY_IN_SECOND + "' SECOND")
.build());
//Register the table for use in SQL queries
tableEnv.createTemporaryView("InputTable", inputTable);
Table resultTable = tableEnv.sqlQuery(
"SELECT " +
" userId," +
" eventEpoch," +
" AVG(valueA) OVER w1 AS AVG_VALUE_B" +
" FROM InputTable " +
" WINDOW w1 AS (" +
" PARTITION BY userId ORDER BY rowtime" +
" RANGE BETWEEN INTERVAL '" + INTERVAL_A + "' SECOND PRECEDING AND CURRENT ROW)"
);
Table resultTable2 = tableEnv.sqlQuery(
"SELECT " +
" FIRST_VALUE(valueB) OVER w1 AS FIRST_VALUE_B," +
" LAST_VALUE(valueB) OVER w1 AS LAST_VALUE_B," +
" FIRST_VALUE(eventEpoch) OVER w1 AS FIRST_EVENTTIME," +
" LAST_VALUE(eventEpoch) OVER w1 AS LAST_EVENTTIME," +
" userId, eventEpoch" +
" FROM InputTable" +
" WINDOW w1 AS (" +
" PARTITION BY userId ORDER BY rowtime" +
" RANGE BETWEEN INTERVAL '" + INTERVAL_B + "' SECOND PRECEDING AND CURRENT ROW)"
);
tableEnv.createTemporaryView("ResultTable1", resultTable);
tableEnv.createTemporaryView("ResultTable2", resultTable2);
Table resultTable3 = tableEnv.sqlQuery(
"SELECT ResultTable1.*," +
" ResultTable2.FIRST_VALUE_B," +
" ResultTable2.LAST_VALUE_B," +
" ResultTable2.FIRST_EVENTTIME," +
" ResultTable2.LAST_EVENTTIME" +
" FROM ResultTable1" +
" LEFT JOIN ResultTable2" +
" ON ResultTable1.userId = ResultTable2.userId" +
" AND ResultTable1.eventEpoch = ResultTable2.eventEpoch"
);

ERROR: The conversion of string " Declare #RepInt=" to double is not valid

I have this query
Dim count as integer = 4
Dim sql As String = " DECLARE #rep INT = " + count + "; " + _
" WITH cte AS " + _
" ( " + _
" SELECT TOP (#rep) " + _
" ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS N " + _
" FROM sys.All_Columns ac1 " + _
" CROSS JOIN sys.ALL_Columns ac2 " + _
" ) " + _
" SELECT t.Barcode" + _
" FROM A_Documents t " + _
" CROSS JOIN cte " + _
" where idDocument = 'doc-123456' " + _
" ORDER BY t.Barcode desc; "
If I put a number without a var, ist works:
Dim sql As String = " DECLARE #rep INT = 4; " + _
But when I put my COUNT var, is not work:
Dim sql As String = " DECLARE #rep INT = " + count + "; " + _
And appears this error message:
The conversion of string " Declare #RepInt=" to double is not valid
that's the expected behaviour of the + operator.
when you feed a number variable to it then the system attempts to convert all the other objects to that numeric type to complete the addition, hence the exception.
imho this is a feature because allows you to exactly know what you are concatenating.
the solution:
Dim sql As String = " DECLARE #rep INT = " + count.ToString + "; " + _
When you try to add a string and a number, it will try to convert the string to a number. You can use the & operator instead, which will convert anything that isn't a string to a string:
Dim sql As String = " DECLARE #rep INT = " & count & "; " + _

How to select all tables from the database?

Good afternoon, whatever your timezone is ..
My question is,
Is there a way to select all tables? just like how we select all columns?
Something like
Dim cmdsql As String = "SELECT * FROM *"
Situation:
I have 4 tables inside the database ("which I would not know the names if my client changes it") So I need a better way how to do those.
I wanna SELECT all the columns, FROM all the tables store it in a dataset, so I can iterate
if it matches the search criteria.
EDIT: This is my search code by the way.
SearchDataset.Clear()
lstSearchResults.Items.Clear()
btnSearch.Enabled = False
Dim cmdsql As String = "SELECT * FROM *" '- This variable holds the SQL command.
'-----------------------------------------
' Connect to the current connection string
'----------------------------------------
SYSTEM_MainClient.dbcon.Open()
'-----------------------------------------
' Setup the Where Clause
'----------------------------------------
If cboSearchBy.Text = "StudentID" Then
SearchAdapter = New OleDb.OleDbDataAdapter(cmdsql + " WHERE " + cboSearchBy.Text + " = " + txtSearchbox.Text, SYSTEM_MainClient.dbcon)
ElseIf cboSearchBy.Text = "Age" Then
SearchAdapter = New OleDb.OleDbDataAdapter(cmdsql + " WHERE " + cboSearchBy.Text + " = " + txtSearchbox.Text, SYSTEM_MainClient.dbcon)
Else
SearchAdapter = New OleDb.OleDbDataAdapter(cmdsql + " WHERE " + cboSearchBy.Text + " like '" + txtSearchbox.Text + "'", SYSTEM_MainClient.dbcon)
End If
SearchAdapter.Fill(SearchDataset, "SearchResults")
SYSTEM_MainClient.dbcon.Close()
If SearchDataset.Tables("SearchResults").Rows.Count > 0 Then
For i = 0 To SearchDataset.Tables("SearchResults").Rows.Count - 1
lstSearchResults.Items.Add(SearchDataset.Tables("SearchResults").Rows(i).Item("Last_Name").ToString + ", " + SearchDataset.Tables("SearchResults").Rows(i).Item("First_Name").ToString)
Next
Else
SYSTEM_MainClient.ShowInformation("No records matched with the search '" + txtSearchbox.Text + "'.", "Database Search")
txtSearchbox.Clear()
End If
btnSearch.Enabled = True
Basically what I want to happen, select all from all tables, and fill it in the dataset and iterate inside the dataset if there are matching result names based on the search criteria with my where clause.
Here this Is the code to select all the tables from the ms access database
SELECT MSysObjects.Name AS table_name FROM MSysObjects
WHERE (((Left([Name],1))<>"~") AND ((Left([Name],4))<>"MSys") AND ((MSysObjects.Type) In (1,4,6)))
order by MSysObjects.Name
Making some alteration to this query will help to select columns of table

Can I use SQLCLR stored procedure to update a column of a database table

I wanted to update the values of a few columns of a database table, using queries or stored procedure, but wanted to use my C# library to alter the value.
For ex, I want the columns A,B,C of table T to be replaced with Encrypt(A), Encrypt(B) and Encrypt(C) where Encrypt is a part of a C# library.
I could have done it in a simple console application, but I have to do this process for a lot of columns in lot of tables. Could I use some SQLCLR stored procedure/query to do this process in SQL Server Management Studio?
It will be really great if someone could assist in this.
public class SP
{
[Microsoft.SqlServer.Server.SqlFunction()]
public static void Enc()
{
using (SqlConnection connection = new SqlConnection("context connection=true"))
{
connection.Open();
SqlCommand command;
SqlCommand command1;
for (int i = 0; i < 1; i++)
{
command = new SqlCommand("SELECT " + tableFieldArray[i, 1].ToString() + " FROM " + tableFieldArray[i, 0].ToString(), connection);
SqlDataReader reader = command.ExecuteReader();
using (reader)
{
while (reader.Read())
{
if (!reader.IsDBNull(0) && !String.IsNullOrEmpty(reader.GetString(0)))
{
//SqlContext.Pipe.Send("Data = " + reader.GetString(0) + "; Encrypted = " + Encrypt(reader.GetString(0)));
SqlContext.Pipe.Send("UPDATE " + tableFieldArray[i, 0].ToString() + " SET "
+ tableFieldArray[i, 1].ToString() + " = '" + Encrypt(reader.GetString(0)) + "' "
+ "WHERE " + tableFieldArray[i, 1].ToString() + " = '" + reader.GetString(0) + "'");
//query = "UPDATE " + tableFieldArray[i, 0].ToString() + " SET "
// + tableFieldArray[i, 1].ToString() + " = '" + Encrypt(reader.GetString(0)) + "' "
// + "WHERE " + tableFieldArray[i, 1].ToString() + " = '" + reader.GetString(0) + "'";
command1 = new SqlCommand("UPDATE " + tableFieldArray[i, 0].ToString() + " SET "
+ tableFieldArray[i, 1].ToString() + " = '" + Encrypt(reader.GetString(0)) + "' "
+ "WHERE " + tableFieldArray[i, 1].ToString() + " = '" + reader.GetString(0) + "'",connection);
}
}
}
SqlCommand command1 = new SqlCommand(query , connection);
command1.ExecuteNonQuery();
}
connection.Close();
}
}
public static string Encrypt(string TextFromForm)
{
//implementation
}
}
}
For some reason this question is a complete duplicate of ( Can I use SQLCLR stored procedure to update a column of a database table ( using some compiled dll) ), but assuming that other one will be closed (it should be), my answer is the same:
You can use SQLCLR to call encryption from C#, though this is the wrong approach. If you need to do a custom algorithm, you should encapsulate that into a SQLCLR function so that it can be used in an UPDATE statement or even an INSERT or SELECT or anywhere. Something like:
public class SP
{
[Microsoft.SqlServer.Server.SqlFunction(IsDeterministic = true)]
public static SqlString EncryptByAES(SqlString TextToEncrypt)
{
return DoSomething(TextToEncrypt.Value);
}
}
Then you can use that function as follows:
UPDATE tb
SET tb.FieldA = EncryptByAES(tb.FieldA)
FROM dbo.TableName tb
WHERE tb.FieldA some_test_to_determine_that_FieldA_is_not_alreay_encrypted;
BUT, before you write a custom encryption algorithm, you might want to check out the several built-in paired ENCRYPTBY / DECRYPTBY functions that might do exactly what you need:
ENCRYPTBYASYMKEY / DECRYPTBYASYMKEY
ENCRYPTBYCERT / DECRYPTBYCERT
ENCRYPTBYKEY / DECRYPTBYKEY
ENCRYPTBYPASSPHRASE / DECRYPTBYPASSPHRASE

Need help in Syntax for accessing data in JSP

I need to access data from a table. I have used the code like this:
string sql = "select * from bikesold "
+ "where model = '"+model+"'
+ "and mnth = '"+mnth+"' ";
The error is coming as follows:
ORA-00904: "MNTH": invalid identifier.
All the database connections are ok. I just need to confirm the Syntax for this code.
string sql = "select * from bikesold "
+ "where model = '"+model+"'"
+ "and mnth = '"+mnth+"' ";
you have missed the double quote in 2nd string.
For starters, your string is wrong. Try this instead:
string sql = "select * from bikesold "
+ "where model = '"+ model +
+ "' and mnth = '"+ mnt + "'";
Q: Does your table actually have a column named "mnth'?

Resources