SQL : how to use IN keyword with prepared statement for range replacement using Java - sql

String sql = "select * from file_repo_index where id in (?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString (1, toCommaSeparatedList(repoIdList));
ResultSet result = ps.executeQuery();
public static String toCommaSeparatedList(Collection col);
I have to use the query as
select * from file_repo_index where id in ( 1,2,3,4 )
But it gives following error in executeQuery() statement
java.sql.SQLException: Conversion failed when converting the nvarchar value '213304,213305,213307' to data type int.
I can use it like
String sql = "select * from file_repo_index where id in ("+toCommaSeparatedList(repoIdList)+")";
Statement ps = conn.createStatement();
ResultSet result = ps.executeQuery(sql);
But I want to use the PrepareStatment method. How can I do it. ??

You should create your prepare statement placeholders based on your values, for instance:
String sql = "select * from file_repo_index where id in (";
//append ?, in above sql in a loop
//Then prepare statement.
This will involve a bit of extra coding, but i think this is the only way to force using PreparedStatement.

If You want to use IN keyword then inside the brackets you have to put like
('213304','213305','213307')
as seperate variables and dont combine in a single "single quotes the entire values" and also in the select statement
String sql = "select * from file_repo_index where id in ("+toCommaSeparatedList(repoIdList)+")";
Change the double quotes to single and try
('+ toCommaSeparatedList(repoIdList) +')";

Related

java.sql.SQLSyntaxErrorException: ORA-00933: SQL command not properly ended with WHERE clause

I am trying to execute a query in my Oracle database with a WHERE clause:
java.sql.Date today = new java.sql.Date(System.currentTimeMillis());
String sql = new StringBuilder("SELECT *")
.append("FROM USERNAME.MY_TABLE m")
.append("WHERE m.A_DATE_COLUMN = ?").toString();
PreparedStatement ps = con.prepareStatement(sql);
ps.setDate(1, today);
ResultSet rs = ps.executeQuery();
But I keep getting error:
SQL command not properly ended
when executeQuery() is called. I know it has to do with setting my parameters because the query runs fine and returns the proper data if I don't include the WHERE clause. The table I am querying from has just the one column which is of type DATE.
I tried using setString instead of setDate and adding a semicolon after ? inside my String I use to create my query, but it's my understanding I don't want to include a semicolon.
You need to add spaces:
String sql = new StringBuilder("SELECT * ")
.append("FROM USERNAME.MY_TABLE m ")
.append("WHERE m.A_DATE_COLUMN = ? ").toString();
After the append, your query looks like below.
SELECT *FROM USERNAME.MY_TABLE mWHERE m.A_DATE_COLUMN = ?
Add the spaces properly.
String sql = new StringBuilder("SELECT * ")
.append("FROM USERNAME.MY_TABLE m ")
.append("WHERE m.A_DATE_COLUMN = ?").toString();

sql statement single quote double quote - Either BOF or EOF is true

Can you please help me with my sql statement? both studentID and password are text.
I thought I figured out the single quote and double quote but apparently not as i am getting the error " Either BOF or EOF is True, or the current record has been deleted. Requested operation requires a current record ".
There is records in my table members.
var mycon;
mycon = new ActiveXObject("ADODB.Connection");
var myrec ;
myrec= new ActiveXObject("ADODB.Recordset");
mycon.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Database2.mdb");
var txtpassword = Request.QueryString("txtpassword");
var txtuserID = parseInt (Request.QueryString("txtuserID"));
var sql;
sql = "SELECT * FROM Members WHERE StudentID='"+txtuserID+"'AND Password='"+txtpassword+"'";
myrec.Open (sql, mycon);
Your syntax looks incorrect as you do not have a space between the txtuserID value and your and in your sql var. It should look like this
"SELECT * FROM Members WHERE StudentID = '"+txtuserID+"' AND Password
='"+txtpassword+"'";
txtuserID = parseInt (Request.QueryString("txtuserID"));
You are parsing the txtuserID to an INT.
You should not put it in quotes, so you could change your SQL to:
"SELECT * FROM Members WHERE StudentID= "+txtuserID+" AND Password='"+txtpassword+"'";
Correct me if I'm wrong, but in:
var sql;
sql = "SELECT * FROM Members WHERE StudentID='"+txtuserID+"'AND Password='"+txtpassword+"'";
The SQL statement in the text isn't finished with a ";".

Query to retrieve all row data for supplied column name

I am using Eclipse and Oracle SQL Developer. My connections are all set up. I am trying to query my database in SQL Developer by passing in a column name as a variable.
For example, I just want to use something similar to this statement:
select * from CUSTOMERS;
but allow CUSTOMERS to be a variable where I can pass in any table name.
Currently this pulls all column names from given column name and connection:
final String query = "select column_name from all_tab_columns"
+" where owner = ?"
+" and table_name = ?";
try {
headers = DAO.useJNDI(jndi)
.setSQL(query)
.input(1, host)
.input(2, tableName)
.list(String.class);
I want to do the same thing but with rows. Does anyone know how to do this? This is what I am thinking about so far:
final String sql = "select *"
+ " from table_name"
+ " where owner = ? and table_name = ?";
try {
logger.debug(tableName+sourceJNDI);
sourceList = DAO.useJNDI(sourceJNDI)
.setSQL(sql)
.input(1, host)
.input(2, tableName)
.list(DatabaseCompareDto.class);
The main focus is the SQL statements. I know everything else works.
If I'm reading your question correctly, I think what you want is to replace the first table_name in your SQL with ?, then add an additional .input( 1, tableName) :
final String sql = "select *"
+ " from ?"
+ " where owner = ? and table_name = ?";
try {
logger.debug(tableName+sourceJNDI);
sourceList = DAO.useJNDI(sourceJNDI)
.setSQL(sql)
.input(1, tableName)
.input(2, host)
.input(3, tableName)
.list(DatabaseCompareDto.class);
You can't pass the table name as a parameter. Instead of wasting your energy on such an alleged generic solution, use or create a small templating engine which allows you to replace the table name in your query before sending it to the database.

Casting ##IDENTITY to Long (Int32) in an Access SQL query

I want to use this syntax but I cant:
Select (Clng ( ##IDENTITY ) )
Or
Clng ( select ( ##IDENTITY ) )
I want to get last inserted id in current scope and cast it to the Long type..how can I make this in one query?
..
This query worked correctly:
Select ##identity
And give me the last inserted autonumber in current session but I want to cast it to the something else in one query
In the first query , You are converting a value into long while you are retrieving it, which is a valid operation.
When you use second query , when select statement is used, you are getting a record set and not an single value.
You can not apply clng on result set but you can apply on a single value
Updated Code:
Check the sample code below:
string query = "Insert Into Categories (CategoryName) Values (?)";
string query2 = "Select ##Identity";
long ID;
string connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb";
using (OleDbConnection conn = new OleDbConnection(connect))
{
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.AddWithValue("", Category.Text);
conn.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = query2;
ID = (long)cmd.ExecuteScalar();
}
}
I just gave the C# version of code as i was not much aware of VB or VB.Net . More over , methodology is the same

SQL - Using a prepared statement for the FROM clause?

Is it possible to use a prepared statement for the FROM clause?
I'm trying to do this:
PreparedStatement preStmType = conn.prepareStatement("SELECT * FROM ? WHERE article_id = ?");
preStmType.setString(1, rsetArticle.getString(5));
preStmType.setInt(2, rsetArticle.getInt(1));
It does not seem to work. When I remove the argument for the FROM clause and use it only in the where, it works, but I would like to generate the FROM dynamically too.
Nope, you can't
Prepared statements supports data literals only.
Speaking of this particular case, why do you want to generate fieldlist dynamically? If you don't know what field you need - just select all and then pick one from the returned row
Are you using Java?
How about trying this:
String qryStr = "SELECT * FROM "+rsetArticle.getString(5)+" "
qryStr =qryStr + "WHERE article_id = ?"
PreparedStatement preStmType = conn.prepareStatement(qryStr);
preStmType.setInt(1, rsetArticle.getInt(1));