How to use array passed from executeWithArray(Object[]) in sql Query - jdo

Iam using the executeWIthArray() to pass a list. But when i try to use this array in Query it shows error.This is my code
QueryHelper.setSortOrderZero(pm).executeWithArray(list);
And in QueryHelper i have defined the function setSortOrderZero as follows:
public static Query setSortOrderZero(PersistenceManager pm) {
final Query query = pm.newQuery("javax.jdo.query.SQL","update TABLENAME set SORTORDER = 0 where ID in list");
return query;
}
But iam getting error.So is this the correct way to access the array????
ERROR:
Exception in ProtectedFilter: Error executing SQL query "update PROFILEARTADS set SORTORDER = 0 where PROFILE_ID in list".
Mar 19, 2015 4:51:44 PM com.sun.jersey.spi.container.ContainerResponse mapMappableContainerException
SEVERE: The RuntimeException could not be mapped to a response, re- throwing to the HTTP container
javax.jdo.JDODataStoreException: Error executing SQL query "update PROFILEARTADS set SORTORDER = 0 where PROFILE_ID in list".
at org.datanucleus.api.jdo.NucleusJDOHelper.getJDOExceptionForNucleusException(NucleusJDOHelper.java:422)
at org.datanucleus.api.jdo.JDOQuery.executeWithArray(JDOQuery.java:321)
at com.giri.artsite.server.per.PersistenceDelegate.deleteAllArtsduplicate(PersistenceDelegate.java:8499)
at com.giri.artsite.server.res.PersonServiceResource.deleteAllArts(PersonServiceResource.java:4681)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
NestedThrowablesStackTrace:
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'list' at line 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3256)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1313)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1585)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1500)
at c

As said, in SQL a "parameter" has to be a "?" in the query; you have no parameter so no point passing in some array of parameters.
What would make more sense would be
q = pm.newQuery("javax.jdo.query.SQL", "update TABLENAME set SORTORDER = 0 where ID in ?");
List values = ...
q.execute(values);

Related

Sqlite database returns nonexistant column name instead of exception due to bad query

Found the issue:
SqlKata compiler was transforming the column names into string literals, so that was returned when a matching column was not located.
Updating the queries to use brackets instead of quotes resolved the issue.
Created github issue here regarding the issue: https://github.com/sqlkata/querybuilder/issues/655
Initial post contents retained below.
I was doing some unit testing against a Sqlite database, ensuring that my methods for creation and reading all work fine (They do). But One of the tests failed, and I am absolutely confused as to why.
The Sqlite db consists of a single table, defined below:
TableName: Students
Columns: ID (Primary Key), FirstName (string), LastName (string)
The following query works properly, returning the 'FirstName' value within the db:
"SELECT \"FirstName\" FROM \"Students\" WHERE \"ID\" = #p0"
The following query I would expect would cause an exception, since the column name does not exist:
"SELECT \"UnknownCol\" FROM \"Students\" WHERE \"ID\" = #p0"
Instead, I receive the value 'UnknownCol' as a string result.
For reference, I’m using the same method (which processes a DbCommand object) to perform the same thing at against an Excel file via OledbCommand. That function produces an exception (not a helpful one, but atleast it error our). So I know the underlying method works.
Why would sqlite return the name of a column that doesn't exist in that query?
Additional Info Edit:
Using an OledbConnection to read from an Excel sheet using the same method results in the following exception when I request an invalid column within the query (which while it doesn't tell you its a bad query due to invalid column name, atleast it errors out):
Exception Message: No value given for one or more required parameters.
Full code chain:
//db object has a method that returns a SqliteConnection, and has a 'Compiler' property that returns the SqlKata.Compiler object for SqlLite
var qry = new SqlKata.Query("Students").Select("UnknownCol").Where("ID",1);
return GetValue(db.GetConnection(), qry, db.Compiler);
//Results in the following sql:
"SELECT \"UnknownCol\" FROM \"Students\" WHERE \"ID\" = 1"
---
public static object GetValue(DbConnection connection, Query query, SqlKata.Compilers.Compiler compiler)
{
using (var cmd = connection.CreateCommand(query, compiler))
{
connection.Open();
try
{
return cmd.ExecuteScalar();
}
finally
{
connection.Close();
}
}
}
public static DbCommand CreateCommand(this DbConnection connection, SqlKata.Query query, SqlKata.Compilers.Compiler compiler)
{
if (connection is null) throw new ArgumentNullException(nameof(connection));
if (compiler is null) throw new ArgumentNullException(nameof(compiler));
var result = compiler.Compile(query ?? throw new ArgumentNullException(nameof(query)));
var cmd = connection.CreateCommand();
cmd.CommandText = result.Sql;
foreach (var p in result.NamedBindings)
{
_ = cmd.AddParameter(p.Key, p.Value);
}
return cmd;
}
public static DbParameter AddParameter(this DbCommand command, string name, object value)
{
var par = command.CreateParameter();
par.ParameterName = name;
par.Value = value;
command.Parameters.Add(par);
return par;
}
It's legal to select a string litteral in SQL. This is a valid SQL query which returns the mentioned string:
SELECT 'UnknownCol';
It will return a single row containing this string litteral.
The following query is similar
SELECT 'UnknownCol' FROM students;
For each row in your table, it will return a row with this string litteral.
Here is an example on a test table with a few rows in a test database:
sqlite> select 'a string litteral' from test;
a string litteral
a string litteral
a string litteral
a string litteral
a string litteral
sqlite> select count(1) from test;
5
sqlite>
If you want to query a specific column name instead of a string litteral you have to remove the '' characters around the column name.
Then this is the result with an undefined column:
sqlite> select unknowncol from test;
Parse error: no such column: unknowncol
select unknowncol from test;
^--- error here
sqlite>
or for a defined column:
sqlite> select id from test;
1
2
3
4
6
sqlite>

Stored Procedures in EF Core 3.0

How to use stored procedures in EF Core 3.0 ?
I have tried the following
var user = await _context.Query<User>().FromSql("EXECUTE dbo.spGeneral_Authenticate").FirstOrDefaultAsync();
var user = await _context.Query<User>().FromSqlRaw("EXECUTE dbo.spGeneral_Authenticate").FirstOrDefaultAsync();
var user = await _context.Set<User>().FromSql("EXECUTE dbo.spGeneral_Authenticate").FirstOrDefaultAsync();
var user = await _context.Set<User>().FromSqlRaw("EXECUTE dbo.spGeneral_Authenticate").FirstOrDefaultAsync();
EF core translating the SQL in wrong way. I got the translated SQL from log file.
2019-09-27 11:21:36.086 +05:30 [Error] Failed executing DbCommand
("30"ms) [Parameters=[""], CommandType='Text', CommandTimeout='30']"
""SELECT TOP(1) [u].[FullName], [u].[Password], [u].[UserName] FROM (
EXECUTE dbo.spGeneral_Authenticate ) AS [u]" 2019-09-27 11:21:36.154 +05:30 [Error] An exception occurred while iterating over
the results of a query for context type '"__________Context"'."
""Microsoft.Data.SqlClient.SqlException (0x80131904): Incorrect syntax
near the keyword 'EXECUTE'. Incorrect syntax near ')'.
Translated SQL:
SELECT TOP(1) [u].[FullName], [u].[Password], [u].[UserName]
FROM (
EXECUTE dbo.spGeneral_Authenticate
) AS [u]
Microsoft.Data.SqlClient.SqlException (0x80131904): Incorrect syntax
near the keyword 'EXECUTE'. Incorrect syntax near ')'.
For the above error, we should use .ToList() or .ToListAsync() not .FirstOrDefault() or .FirstOrDefaultAsync()
It will work
var user = await _context.Set<User>().FromSql("EXECUTE dbo.spTest").ToListAsync();
It won't work
var user = await _context.Set<User>().FromSql("EXECUTE dbo.spTest").FirstOrDefaultAsync();
/*
Transalated SQL:
SELECT TOP(1) [u].[FullName], [u].[Password], [u].[UserName]
FROM (
EXECUTE dbo.spTest
) AS [u]
*/
The accepted answer nails it. Here are my two cents however:
Also, if you want to get only one result and still want to make the server call asynchronously:
var user = (await _context.Set<User>().FromSql("EXECUTE dbo.spTest").ToListAsync()).FirstOrDefault();

delete query in ssis package with 2 or more parameters in execute SQl Task

I am new to SSIS I want to execute delete query in my SSIS package thorough Execute Sql Task having 2 or more parameters. If I use 1 parameter it's working fine but if more than 1 than error. I don't want to use SP's and please help me as I am stuck from a long time.
General
TimeOut = 0
Typeconversionmode - Allowed
Result Set - None
ConnectonType - OLE DB
Connection = MyConnection
SqlSource = DirectInput
SqlStatment="delete from tblStgPaymentProcessingACH where id=? and paymentid=?"
BypassPrepare = True
Variables
Name = ID , Scope = MyJOB, DataType=int64, Value=2
Name = PMTID , Scope = MyJOB, DataType=int64, Value=101161419602
Parameter Mapping
User::ID, Direction = input, datatype = LONG, ParameterName = 0, ParamtereSize = 0
User::PMTID, Direction = input, datatype = LONG, ParameterName = 1, ParamtereSize = 0
Database DataTypes
Column
ID - INT
Paymentid - Bigint
Getting Error
[Execute SQL Task] Error: Executing the query "delete from mytable
where id=..." failed with the following error: "An error occurred while extracting the result into a variable of type (DBTYPE_I4)". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.

Azure Cosmos DB: Incorrect syntax near 'Dec' error while executing query through stored procedure

In a stored procedure that runs against the Azure Cosmos DB non-partitioned collection, I am running below select query:
var twentyMinutesBefore = new Date();
twentyMinutesBefore.setMinutes(twentyMinutesBefore.getMinutes() - 20);
var filterQuery = "SELECT TOP 40 * FROM c WHERE (c.transmissionState = 2 AND (" + twentyMinutesBefore + " > c.dateCreated.epoch)) OR c.transmissionState = 0 ORDER BY c.dateCreated.epoch DESC";
I execute the query as below:
var isAccepted = collection.queryDocuments(collectionLink, filterQuery, options, callback);
function callback(err, queryFeed, responseOptions) {
if (err) {
throw err; // <-- Error thrown from this line as per stack trace
}
// Iterate through query feed
}
I get the below error:
"Message": "Microsoft.Azure.Documents.DocumentClientException: Message:
{\"Errors\":[\"Encountered exception while executing function. Exception = Error:
{\\"errors\\":[{\\"severity\\":\\"Error\\",\\"location\\":{\\"start\\":63,\\"end\\":66},\\"code\\":\\"SC1001\\",
\\"message\\":\\"Syntax error, incorrect syntax near 'Dec'.\\"}]}
Stack trace: Error: {\\"errors\\":[{\\"severity\\":\\"Error\\",\\"location\\":{\\"start\\":63,\\"end\\":66},\\"code\\":\\"SC1001\\",\\"message\\":\\"Syntax error, incorrect syntax near 'Dec'.\\"}]}
In a Console application, I tried resolving the filter query to verify if it is properly formatted. It results as below:
SELECT TOP 40 * FROM c WHERE (c.transmissionState = 2 AND (1512593297244 > c.dateCreated.epoch)) OR c.transmissionState = 0 ORDER BY c.dateCreated.epoch DESC
When I copy this query as is and run in Cosmos DB query window, it runs fine and returns results as expected.
Not sure why it doesn't run through the stored procedure. Any idea what that 'Dec' means in the error? I don't find any such string in my stored procedure.
Use twentyMinutesBefore.getTime(), without getTime() to get the UNIX epoch time, you will get the full date like "Thu Dec 07 2017 13:26:39 GMT+1100 (AUS Eastern Daylight Time)":
var filterQuery = "SELECT TOP 40 * FROM c WHERE (c.transmissionState = 2 AND (" + twentyMinutesBefore.getTime() + " > c.dateCreated.epoch)) OR c.transmissionState = 0 ORDER BY c.dateCreated.epoch DESC";

InvalidOperationException: The null value cannot be assigned .... when calling SubmitChanges

I have a table A with an Identity column.
When I insert a row via visualStudio it failed in the SubmitChanges with the following error:
InvalidOperationException: The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type
I searched about this in google and I found some discussions about the same issue. one of them is Here.
it says that it's because the procedure returns a null value.
I did as is wrote there. used sql trace, copy the insert command and run it in sql server.
it realy returns null but the row was inserted correctly!!!
the command as it is in the sql trace:
exec sp_executesql N'INSERT INTO [dbo].[MyName_Tbl]([x], [y], [z], [c], [v], [b], [n], [m], [a], [s], [d], [f], [g], [h], [j], [k], [l], [q], [w], [e], [r])
VALUES (#p0, #p1, #p2, #p3, #p4, #p5, #p6, #p7, #p8, #p9, #p10, #p11, #p12, #p13, #p14, #p15, #p16, #p17, #p18, #p19, #p20)
SELECT CONVERT(Int,SCOPE_IDENTITY()) AS [value]',N'#p0 varchar(8000),#p1 varchar(8000),#p2 nvarchar(4000),#p3 nvarchar(4000),#p4 varchar(8000),#p5 nvarchar(4000),#p6 varchar(8000),#p7 varchar(8000),#p8 nvarchar(4000),#p9 nvarchar(4000),#p10 nvarchar(4000),#p11 nvarchar(4000),#p12 nvarchar(4000),#p13 varchar(8000),#p14 varchar(8000),#p15 nvarchar(4000),#p16 varchar(8000),#p17 nvarchar(4000),#p18 nvarchar(4000),#p19 nvarchar(4000),#p20 decimal(5,2)',#p0='406',#p1='Kabala',#p2=N'01/05/2012 13:47:01',#p3=N'k406/00033',#p4='406/00033',#p5=N'xxx',#p6='127.0.0.1',#p7='10',#p8=N'yyy',#p9=N'hh hh',#p10=N'0527159080',#p11=N'',#p12=N'',#p13='4580',#p14='1',#p15=N'Visa',#p16='0115',#p17=N'10',#p18=N'0',#p19=N'0232323',#p20=0
Can you explain me what's the problem and why in sql it executed correctly and in VS I get an error?
The error you are receiving has nothing to do with an invalid SQL statemt which explains why it works fine when you execute it directly on SQL Server.
The error is being thrown on your app and it's simply because the SQL statement is supposed to return an int containing the value of the last id inserted in the table but instead is returning a NULL value, which makes your program choke since null cannot be assigned to an int unless you declare it as a Nullable<int> (int?)

Resources