Pass a single parameter and a parameter List with Spring's JDBCTemplate (namedJDBCTemplate) - spring-jdbc

How to code such a simple SQL with Spring JDBC ?
UPDATE tableA SET column1 = var1 WHERE column1 IN (var2, var3, ...);
where var1 is dynamic variable and var2, var3, ... - dynamic variable list.

Without the IN , you can do like this:
PreparedStatement ps = connection.prepareStatement("UPDATE tableA SET column1 = ? WHERE column1 =? ");
ps.setString(1, var1);
ps.setString(2, var2);
And about how to deal with In I hope this may give you some clue.
After some search, I also found this question may help you:
PreparedStatement with list of parameters in a IN clause
How to set list of parameters on prepared statement?
PreparedStatement IN clause alternatives?

Related

The multi-part identifier could not be bound error won't fix

The Variable fileName contains the name of two columns to fetch value of it, which is in the type of "email,address"
The output of the fileName variable is sam#gmail.com102streetN, which is what I need
but when I try to insert that value into another column table then it throws me an error
The multi-part identifier "sam#gmail.com102streetN" could not be bound.
I don't know how to fix it
for each a in idParase
strSQL = "Select Award, Year, ("&fileName&") as dynamicColumns FROM dbo.Awards_TABLE Where awardID = "&a&""
cmdCRProc.CommandText = strSQL
Set rsCR = cmdCRProc.Execute
nameParase = rsCR("dynamicColumns")
sql2 = "Insert Into dbo.Queue (Award,Year,awardID,FileName) Values ("&rsCR(0)&", "&rsCR(1)&", "&a&", "&nameParase&") "
cmdCRProc.CommandText = sql2
Set rsCR = cmdCRProc.Execute
next
I think this isn't going wrong in the INSERT, but in the SELECT.
If I write out your SELECT it would be something this I think (I don't know the value of "a", but let's say it's 2):
Select Award, Year, (sam#gmail.com102streetN) as dynamicColumns FROM dbo.Awards_TABLE Where awardID = 2
I very much doubt you have a column named 'sam#gmail.com102streetN', right?
I don't know what your goal is, but it seems like you're building a query with a dynamic column name that doesn't exist.
What you can do is Response.Write() your SQL statements and see what the result is. Then maybe run them in your database management tool to check what's going on:
Response.write(strSQL)
And
Response.write(sql2)

Aggregation Queries

Is it possible to do the following query in SQLite.Swift without resorting to arbitrary SQL (which I do have working but would prefer to avoid)?
select table1.id, sum(table1.col1*table2.col2)
from table1, table2
where table1.id=table2.id
group by table1.id
I've attempted the following: the SQL (through asSQL()) appears to be correct, but I can't find a way to reference the aggregate column from the returned row.
let query = table1.select(id, (table1[column1]*table2[column2]).sum
.join(table2, on: table1[id] == table2[id])
.group(id)
Can you alias columns somehow?
OK, I've found the solution, and it only took me 2 days!
The way to alias a column in SQLite.swift is to use an expression.
The name of the expression becomes the column alias.
So instead of
let query = table1.select(id, (table1[column1]*table2[column2]).sum)
.join(table2, on: table1[id] == table2[id])
.group(id)
Use:
let aggrColumn = (table1[column1]*table2[column2]).sum
let query = table1.select(id, aggrColumn)
.join(table2, on: table1[id] == table2[id])
.group(id)
let results = try db.prepare(query)
for row in results {
myAggrColumn = try row.get(aggrColumn)
}
Using
select id, sum(table1.col1*table2.col2)
from table1, table2
were table1.id=table2.id
group by id
Will result (see below for corrections) in 2 columns, namely id and sum(table1,col*table2.col2)
However both uses of id would be ambiguous as coded as there are two such source columns.
As such the query should be changed (see following code whihc assumes you want the id from table1 (shouldn't matter if table2 were used due to the join))
Additionally were is not a keyword, it should be WHERE
An alias would likely make things easier you make an alias using the AS keyword. The folloiwng also includes AS mysumcolumn thus the resultant columns will be id and mysumcolumn
select table1.id, sum(table1.col1*table2.col2) AS mysumcolumn
from table1, table2
where table1.id=table2.id
group by table1.id
Running this with no data results in :-

Creating a new table in sqlite database [duplicate]

I'm having some strange feeling abour sqlite3 parameters that I would like to expose to you.
This is my query and the fail message :
#query
'SELECT id FROM ? WHERE key = ? AND (userid = '0' OR userid = ?) ORDER BY userid DESC LIMIT 1;'
#error message, fails when calling sqlite3_prepare()
error: 'near "?": syntax error'
In my code it looks like:
// Query is a helper class, at creation it does an sqlite3_preprare()
Query q("SELECT id FROM ? WHERE key = ? AND (userid = 0 OR userid = ?) ORDER BY userid DESC LIMIT 1;");
// bind arguments
q.bindString(1, _db_name.c_str() ); // class member, the table name
q.bindString(2, key.c_str()); // function argument (std::string)
q.bindInt (3, currentID); // function argument (int)
q.execute();
I have the feeling that I can't use sqlite parameters for the table name, but I can't find the confirmation in the Sqlite3 C API.
Do you know what's wrong with my query?
Do I have to pre-process my SQL statement to include the table name before preparing the query?
Ooookay, should have looked more thoroughly on SO.
Answers:
- SQLite Parameters - Not allowing tablename as parameter
- Variable table name in sqlite
They are meant for Python, but I guess the same applies for C++.
tl;dr:
You can't pass the table name as a parameter.
If anyone have a link in the SQLite documentation where I have the confirmation of this, I'll gladly accept the answer.
I know this is super old already but since your query is just a string you can always append the table name like this in C++:
std::string queryString = "SELECT id FROM " + std::string(_db_name);
or in objective-C:
[#"SELECT id FROM " stringByAppendingString:_db_name];

Android SQLITE Insert into table with values coming from a subquery

In my db-driven app I need to perform insert into queries in which the value for one or more field comes from a subquery.
The insert into statement may look like the following example:
INSERT INTO MyTable (field_1, field_2)
VALUES('value for field 1', (SELECT field_x FROM AnotherTable WHERE ...))
At present I am doing it manually building the query:
String MyQuery = "INSERT INTO mytable (field_1, field_2)
VALUES('value for field 1', (SELECT field_x FROM AnotherTable WHERE ...))"; // Of course my query is far more complex and is built in several steps but the concept is safe, I end up with a SQL String
SQLiteDatabase= db = getWritableDatabase();
db.execSQL(MyQuery); // And it works flawlessy as it was a Swiss Clock
What i would like to do instead is:
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put("field_1", "value for field 1");
values.put("field_2", ThisIsAQuery("(SELECT field_x FROM AnotherTable WHERE ...)"));
db.insert("MyTable", null, values);
db.close();
Where the fake method ThisIsAQuery(...) is the missing part, something that should tell the query builder that "SELECT.." is not a value but a query that should be embedded in the insert statement.
Is there a way to achieve this?
The whole point of the ContentValues container is to be able to safely use strings without interpreting them as SQL commands.
It is not possible to use subqueries with insert(). The only way to get a value from another table is by executing a separate query; in this case, ThisIsAQuery() would be stringForQuery() or longForQuery().

JDBC - SQLITE Select to variable

I am trying to run a query / select statement and save it in a variable. I know how to get something specific from a specific column but not from counting rows.
This is working as I getting MYID specifically.
ResultSet MYIDrs = stmtCFG.executeQuery( "SELECT rowid, MYID from MYINDEX order by rowid desc limit 1;" );
MYID = MYIDrs.getString("MYID");
Now I am trying to count the rows that works in SQLite client but not in the jdbc as I can't figure out what to request.
this is what I have but is not resulting in what I am expecting.
ResultSet FILE_COUNTrs = stmtCFG.executeQuery( "SELECT count(*) from TABLE where MYID = '"+MYID+"';");
FILE_COUNT = FILE_COUNTrs.getString(?????);
problem or question is: What do I put in the ????? as I already tried everything.
I am expecting to see a number.
I am really sorry I found what I was looking for by assigning a name TOTAL
This is my code and it works...
ResultSet FILE_COUNTrs = stmtCFG.executeQuery( "SELECT count(*) AS TOTAL from TABLE where MYID = '"+MYID+"';");
FILE_COUNT = FILE_COUNTrs.getString("TOTAL");
You use wrong data type. COUNT(*) returns Integer type, Not String.
You can do like this without assigning a label for COUNT(*)
int FILE_COUNT = FILE_COUNTrs.getInt(1); // 1: is the column index of COUNT(*)

Resources