How to use a variable inside an sql query - sql

I have a query such this (i put it into a string for preparation of the query itself):
select r.id,
r.id_user,
r.date_pubblication,
r.name,
r.description,
r.type,
u.name as Uname
from resources r,
users u
where r.id_user=id_logged
Now all these fields in the select are field of DB tables . Only id_logged is not a field of a table but is a java variable defined by this way:
User user = userService.getUserCurrent();
long id_logged = user.getId();
The error returned after running the query is
ORA-00904: "ID_LOGGED": invalid identifier
Something more to say is that when I define id_logged by giving the value user.getId(), there is a warning
- The value of the local variable id_logged is not used
Can you explain what is my mistake? I can I run this query correctly ?

So If I understand correctly, you generate somtehing like this:
"select r.id, r.id_user, r.date_pubblication,r.name, r.description, r.type, u.name as Uname from resources r, users u where r.id_user=id_logged"
as a string ?
If so - check the last parameter: r.id_user=id_logged.
It is a string. And you declare the id_logged as a javascript variable.
If so - you have to join the string of your query , with the variable value.
For example in:
javascript:
"query string" + id_logged
php:
"query string" . id_logged
This should help you - IF i understood your question correctly.

If your query is a Java string, you need to do something like this:
String id_logged = //Whatever you do to get the value of id_logged.
String query = "select r.id, "+
"r.id_user, "+
"r.date_pubblication,"+
"r.name,"+
"r.description, "+
"r.type, "+
"u.name as Uname "+
"from resources r, "+
"users u "+
"where r.id_user="+id_logged ;
//Now you can execute the query.
Be aware that this is prone to SQL injection. You really should be doing this sort of thing with prepared statements.

Related

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.

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));

Keyword search to include Uniqueidentifier field

I'm wanting to let a user search rows in a database by specifying a keyword to look for. There are a few fields I would like to look in for this keyword, one of which is a uniqueidentifier. The problem is, if the keyword is not a GUID, I get the following error message:
Conversion failed when converting from a character string to uniqueidentifier
The SQL I'm using to run the search looks something like this:
// do not use
string sql = #"SELECT *
FROM [MyTable]
WHERE [MyTable].[TableID] = '" + keyword + "'";
WARNING: this is just example code - DO NOT write sql commands like this as it creates a security risk
How do I write my SQL select statement such that it will not fail when keyword is not a GUID?
string sql;
Guid id;
if (Guid.TryParse(keyword, out id))
{
sql = #"SELECT *
FROM [MyTable]
WHERE [MyTable].[TableID] = '" + keyword + "'";
}
else
{
sql = //search by other way
}
Does this work for you?
string sql = #"SELECT *
FROM [MyTable]
WHERE convert(varchar,[MyTable].[TableID]) = '" + keyword + "'";
I know this doesn't really help you today, but may help future readers. In SQL Server 2012 you will be able to use TRY_CONVERT:
string sql = #"SELECT *
FROM dbo.[MyTable]
WHERE [TableID] = TRY_CONVERT(UNIQUEIDENTIFIER, '" + keyword + "');";
But what you really should be doing is passing the parameter as a strongly typed GUID, and handling the error (using try/catch) in the client program when someone enters something that isn't a GUID.

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

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) +')";

Getting "The column name xxx is not valid" exception when trying to combine columns

I am trying to combine two columns in SQL query but getting the following exception in java.sql.ResultSet's FindColumn method:
JdbcSqlException: The column name
FullName is not valid. Column:
'FullName'
Here is my SQL query
SELECT U.FirstName + ' ' + U.LastName AS FullName FROM User as U
Anyone?
Please note that query runs fine when I run it directly in SQL Server management studio. Also, this query is part of a big query that's why U as alias.
When you put "AS FullName", Fullname is a label now. JDBC gets data by "column name" or "field name". You have to change your code (I dont know your prog. language) accordingly.
You might try putting parentheses around the string concatenation, as in
SELECT (U.FirstName + ' ' + U.LastName) AS FullName FROM User U
Share and enjoy.
Sorry I am answering this late. I am sure someone will need the answer. I have had the same problem and whereas I do not know exactly why and what causes it, I have found a way to fix it (at least for my case).
jahanzeb farooq did not show his code but if you had declared the PreparedStatement and ResultSet variables variables outside the current method and used them in other queries then try declaring them anew inside the current method, that is
PreparedStatement pst=conn.prepareStetement(sql);
ResultSet rs=pst.executeQuery();
The problem will be sorted (or at least fixed)
String sql = "SELECT U.FirstName + ' ' + U.LastName AS FullName FROM User U ";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
if (rs.next()) {
String fullname = rs.getString("FullName");
jtextfiel.setText(fullname);
//////or - short
jtextfiel.setText(rs.getString("FullName"));
}