Similar question to:
Strange problem with JDBC, select returns null
but people didn't ask for this.
My code:
public int myMethod(String day) throws SQLException{
String sql = "Select count(*) from MyTable WHERE someColumn = " + day;
Connection connection = ConnFactory.get();
PreparedStatement prepareStatement = null;
ResultSet resultSet = null;
int ret = -1;
try{
prepareStatement = connection.prepareStatement(sql);
resultSet = prepareStatement.executeQuery(sql);
if(resultSet.next()){
ret = resultSet.getInt(1);
}
}
catch(SQLException sqle){
// closing statement & ResultSet, log and throw exception
}
finally{
// closing statement & ResultSet
}
ConnFactory.kill(connection);
return ret;
}
This code always return 0. I try to log sql before execution and try to run it in SQLdeveloper and get correct value (over 100).
When I remove WHERE, sql = "Select count(*) from MyTable query return number of all rows in table.
I use Oracle 10g with ojdbc-14.jar (last version from maven repo) and Java 6.
day has not been quoted correctly, I would suggest using a prepared statement like a prepared statement as follows:
...
try {
prepareStatement = connection.prepareStatement("Select count(*) from MyTable WHERE someColumn = ?");
prepareStatement.setString(1,day);
...
is the same as:
sql = "Select count(*) from MyTable WHERE someColumn = '" + day + "'";
with several advantages over the latter (mainly security and performance). See:
http://java.sun.com/docs/books/tutorial/jdbc/basics/prepared.html
First of all using sql like this is not advisable. Because it leads to SQL injection.
In the future try using like below and use PreparedStatement to execute
String sql = "Select count(*) from MyTable WHERE someColumn = ? "
For your solution did you try
String sql = "Select count(*) from MyTable WHERE someColumn = '" + day + "'";
karim79 is good answer, you forgot add apostrophe signs in your "day" value
String sql = "Select count(*) from MyTable WHERE someColumn = '" + day + "'";
Related
Trying to write condition where ind is null in the select query in java using jdbc oracle driver.
code :
Done all the DB connectivity
info.add("CN");
info.add("NULL");
Tried:
ResultSet rs1 = st.executeQuery("select COUNT(*) from TABLENAME where A='" + info.get(i) + " and ind is'" +info.get(i+1) + " '");
Note: using oracle driver JDBC API.
Taking the null value from array list.but it does not fetch proper values from DB.
code:
Done all the DB connectivity
info.add("CN");
info.add("NULL");
ResultSet rs1 = st.executeQuery("select COUNT(*) from TABLENAME where A='" + info.get(i) + " and ind IS '" +info.get(i+1) + " '");
I expect the output like count(no of rows):
BAsic sql query if used in DB:
select COUNT(*)
from TABLENAME
where A= 'a'
and ind IS null;
First handling NULL is different than handling a value:
ind IS NULL
ind = '...'
This makes it difficult to use a prepared statement. But a PreparedStatement should be used, not only for securite (against SQL injection) but also to escape single quotes and such. And is type-safe in that it uses types & conversions.
Oracle SQL has a defect in that it does not distinghuish between NULL and '', so you could go for '' instead. Oracle independent would be:
// Typed fields:
String a = ...;
int n = ...;
String ind = null;
String sql = ind == null
? "select COUNT(*) from TABLENAME where A=? and n=? and ind is null"
: "select COUNT(*) from TABLENAME where A=? and n=? ind = ?";
try (PreparedStatement stmt = new PreparedStatement(sql)) {
stmt.setString(1, a);
stmt.setInt(2, n);
if (ind != null) {
stmt.setString(3, ind);
}
try (ResultSet rs = stmt.executeQuery()) {
long count = rs.next() ? rs.getLong(1) : 0L;
return count;
}
}
Try-with-resources closes statement and result set, also with thrown exception or return in the middle.
For a general Object list, one could use one for loop constructing the SQL template, and a second for setting the PreparedStatement's fields.
This part:
" and ind is'" +info.get(i+1) + " '");
generates the following SQL:
and ind is 'NULL ';
which is wrong because it will throw an error:
ORA-00908: missing NULL keyword
You need to change that to:
" and ind is " +info.get(i+1));
but then it won't work any more for not null values.
Im running the code and keep getting the Resultset is closed, is there something wrong with the loops? The Strings that is taken from the for() has multiple "SUBKATEGORIER" aswell. Pls help me I'm new to Java.
Object[] valt = jList1.getSelectedValues();
for (Object ettVal : valt) {
String enSuperkategori = ettVal.toString();
System.out.println(enSuperkategori);
try {
Statement stmt2 = connection.createStatement();
ResultSet rs2 = stmt2.executeQuery("SELECT SUBKATEGORIID FROM
SUBKATEGORI JOIN SUPERKATEGORI ON SUPERKATEGORI.SUPERKATEGORIID =
SUBKATEGORI.SUPERKATEGORI WHERE SUPERKATEGORI.SKNAMN ='" + enSuperkategori
+"'");
while(rs2.next());
{
PreparedStatement ps2 = connection.prepareStatement("INSERT
INTO ANVANDARE_SUBKATEGORI (ANVANDARE,SUBKATEGORI) VALUES(?,?)");
ps2.setString(1, angivetAnv);
ps2.setInt(2, rs2.getInt("SUBKATEGORIID"));
System.out.println(rs2.getInt("SUBKATEGORIID"));
ps2.executeUpdate();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
I don't know the exact cause of the error, but my guess is that your first result set is getting closed as soon as you run the inner insert. The good news is that you may run your entire insert using the following single query:
INSERT INTO ANVANDARE_SUBKATEGORI (ANVANDARE, SUBKATEGORI)
SELECT SUBKATEGORIID, SUBKATEGORIID
FROM SUBKATEGORI s
INNER JOIN SUPERKATEGORI sp
ON sp.SUPERKATEGORIID = s.SUPERKATEGORI
WHERE sp.SKNAMN = ?
Your relevant Java code:
String sql = "INSERT INTO ANVANDARE_SUBKATEGORI (ANVANDARE, SUBKATEGORI) ";
sql += "SELECT SUBKATEGORIID, SUBKATEGORIID ";
sql += "FROM SUBKATEGORI s ";
sql += "INNER JOIN SUPERKATEGORI sp ";
sql += "ON sp.SUPERKATEGORIID = s.SUPERKATEGORI ";
sql += "WHERE sp.SKNAMN = ?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, enSuperkategori);
ps.executeUpdate();
I want to retrieve a particular column from the database. For a simple Select statement, I can able to able to retrieve a column like below
public String getDbColumnValue(String tableName, String columnName, String applicationNumber) {
String columnValue = null;
try {
PreparedStatement ps = null;
String query = "SELECT " + columnName + " FROM " + tableName +
" WHERE ApplicationNumber = ?;";
ps = conn.prepareStatement(query);
ps.setString(1, applicationNumber);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
columnValue = rs.getString(columnName);
return columnValue;
}
}
catch (Exception ex) {
}
return columnValue;
}
But, I'm using alias in my query like below. And this query works fine. How to use this in Java to retrieve a particular column
select S.StatusDesc from application A, StatusMaster S
where A.StatusMasterId = S.StatusMasterId and A.ApplicationNumber = '100041702404'
Any help would be greatly appreciated!
I think you are confusing simple aliases, which are used for table names, with the aliases used for column names. To solve your problem, you can just alias each column you want to select with a unique name, i.e. use this query:
select S.StatusDesc as sc
from application A
inner join StatusMaster S
on A.StatusMasterId = S.StatusMasterId and
A.ApplicationNumber = '100041702404'
Then use the following code and look for your aliased column sc in the result set.
PreparedStatement ps = null;
String query = "select S.StatusDesc as sc ";
query += "from application A ";
query += "inner join StatusMaster S ";
query += "on A.StatusMasterId = S.StatusMasterId ";
query += "and A.ApplicationNumber = ?";
ps = conn.prepareStatement(query);
ps.setString(1, applicationNumber);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
columnValue = rs.getString("sc");
return columnValue;
}
Note: I refactored your query to use an explicit inner join instead of joining using the where clause. This is usually considered the better way to write a query.
I am trying to write a query and get results from oracle db using java and jdbc. My problem is the same query works if I try with statement, but the same query does not work if I use preparedStatement.
Statement Code: (Here I get real count value)
Statement stmt = con.createStatement();
String sql = "SELECT COUNT(*) CNT FROM DB.TABLE WHERE DAY = TO_DATE('" + sqlDate + "','YYYY-MM-DD')";
rs = stmt.executeQuery(sql);
PreparedStatement Code: (Here I get count value zero)
Date sqlDate = new java.sql.Date(someJava.Util.Date.getTime());// = 2015-09-24
sqlString = "SELECT COUNT(*) CNT FROM DB.TABLE WHERE DAY = TO_DATE(?,'YYYY-MM-DD')";
pstmt = con.prepareStatement(sqlString);
pstmt.setDate(1, sqlDate);
rs = pstmt.executeQuery();
When I sysout my sqlDate prints like: 2015-09-24.
I have same problem with some other queries.
Can anyone know whats wrong here?
The TO_DATE function converts a string to a date given a certain format. So the parameter passed to the prepared statement should be the String to be converted by the Oracle function:
pstmt.setString(1, sqlDate.toString());
Or you can change the query so that the parameter is the date itself and pass the java.sql.Date object to the prepared statement:
sqlString = "SELECT COUNT(*) CNT FROM DB.TABLE WHERE DAY = ?";
pstmt.setDate(1, sqlDate());
Note that, for the normal statement query:
String sql = "SELECT COUNT(*) CNT FROM DB.TABLE WHERE DAY = TO_DATE('" + sqlDate + "','YYYY-MM-DD')";
the String concatenation will append the string representation of the object, i.e. it is equivalent to:
String sql = "SELECT COUNT(*) CNT FROM DB.TABLE WHERE DAY = TO_DATE('" + sqlDate.toString() + "','YYYY-MM-DD')";
How can i find out, from a Java program using JDBC if my table has a record with a specific primary key value? Can i use the ResultSet somehow after i issue a SELECT statement?
Count might be a better idea for this case. You can use it like so:
public static int countRows(Connection conn, String tableName) throws SQLException {
// select the number of rows in the table
Statement stmt = null;
ResultSet rs = null;
int rowCount = -1;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT COUNT(*) FROM " + tableName + " WHERE.... ");
// get the number of rows from the result set
rs.next();
rowCount = rs.getInt(1);
} finally {
rs.close();
stmt.close();
}
return rowCount;
}
Taken from here.
You can do something like
private boolean hasRecord(String id) throws SQLException {
String sql = "Select 1 from MyTable where id = ?";
PreparedStatement ps = dbConn.prepareStatement(sql);
ps.setString(1,id);
ResultSet rs = ps.executeQuery();
return rs.next();
}
You can do that in four steps.
Write SQL. Something like select count(1) from table where column = 34343 will do.
Learn how to get connection using JDBC.
Learn about PreparedStatements in Java.
Learn how to read values from ResultSet.
select case
when exists (select 1
from table
where column_ = '<value>' and rownum=1)
then 'Y'
else 'N'
end as rec_exists
from dual;