Please find my below query,
select nvl(max(transaction_id),0) as transaction_id from exception_details;
If I execute the above query through my jdbc code, it is giving me java.sql.SQLException: Fail to convert to internal representation
my JDBC code is as follows:
public int fetchColumnVal(String query) throws SQLException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException, ClassNotFoundException, InstantiationException {
PreparedStatement pstmt = null;
Connection con = null;
try {
con = getConnection(true);
pstmt = con.prepareStatement(query);
ResultSet rs = pstmt.executeQuery();
rs.next();
int count=rs.getInt(1);
return count;
} finally {
if (isBatchMode) {
this.cleanResources(null, pstmt);
}
else {
this.cleanResources(con, pstmt);
}
}
}
and the data type for the column transaction_id in the table is NUMBER
if you use #Enumerated without define EnumType.STRING, i.e
#Enumerated(EnumType.STRING)
and your table already contain String data (Varchar), you shall get this error, cos.
default EnumType is ORDINAL, i.e EnumType.ORDINAL.
SQL JDBC/Java setXXX getXXX
NUMERIC java.math.BigDecimal setBigDecimal getBigDecimal
change rs.getInt(1); to rs.getBigDecimal(1);
(or) type cast number to integer in sql like below for oracle:
CAST(id AS integer)
I would like to suggest a more traditional approach for ResultSet count checking.
Initially I tried using:
while (RS.next()) {
RScount = RS.getInt(1);
Set.add(RS.getString(1));
}
But as my SQL result-set was String, Java kept on throwing:
java.sql.SQLException: Fail to convert to internal representation
Then I changed my code to to plain Vanilla:
Declaration, initialized at 0:
Integer RScount = 0; //SQL result set counter
And counter code as:
while (RS.next()) {
RScount++;
Set.add(RS.getString(1));
}
I was getting error like
Exception Foundjava.sql.SQLException: Fail to convert to internal representation.
I have written my code as :
while(res.next())
System.out.println( res.getInt(1) + " "
+ res.getString(2) + " "
+ res.getString(3) + " "
+ res.getString(4));
but my datatype of 1st field in DB was of varchar type.
Then I changed my code to:
while(res.next())
System.out.println( res.getString(1) + " "
+ res.getString(2) + " "
+ res.getString(3) + " "
+ res.getString(4));
then I got all my data.
Related
I´m totally new to Java and I try to set up a little test to read some data from a MSSQL-database. I have to pass some values to the query but that does not work properly, if I set them manually it works, in my case with the PreparedStatement and the .setLong-Method it does not work.
public class db_testClass {
public static void main(String[] args) throws ClassNotFoundException {
long firstId = 0;
long lastId = 201801001010010403L;
PreparedStatement statement;
int counter = 1;
String SQL = "IF OBJECT_ID('tempdb..#tmpDaten') IS NOT NULL
" DROP TABLE #tmpDaten;
" SELECT DISTINCT
" RIGHT(10000000 + ISNULL(r.xxx, 0), 7) AS Wert
" INTO #tmpDaten
" FROM dbo.xxx
" WHERE r.xxxx BETWEEN firstId = ? AND lastId = ?;
" SELECT DISTINCT
" 'xxxx' AS Art ,
" t.xxx
" FROM #tmpDaten
" LEFT JOIN xxxxxxx a ON a.xxxx = t.xxxx
" AND a.ART = 'xxxx' " +
" WHERE a.xxxx IS NULL;";
String connectionUrl = "jdbc:sqlserver://xxxxxx:1433;databaseName=xxxxxx;integratedSecurity=true;";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
try {
Connection con = DriverManager.getConnection(connectionUrl);
statement = con.prepareStatement(SQL);
statement.setLong(1, firstId);
statement.setLong(2, lastId);
System.out.println(statement);
ResultSet rs = statement.executeQuery();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
The error says that there is wrong syntax nearby the '='......
Anyone any ideas?
Thanks,
Daniel
Your usage of the BETWEEN operator is suspicious and probably just an outright syntax violation. It should be something like:
something BETWEEN low-value AND high-value
to test if the something lies between the values low-value and hi-value.
I'm trying to get the new id when inserted new data in database table, but I got:
ORA-01008: not all variables bound
I'm doing it from a Java SE project,
public ResultSet ejecutarConsulta(String instruccionSql){
rs = null;
try {
st = con.createStatement();
rs = st.executeQuery(instruccionSql);
System.out.println("Consulta Exitosa");
} catch (SQLException e) {
System.out.println("Error en la Consulta: "+e.getMessage());
}
return rs;
}
And the String "instruccionSql" that i'm passing is
insert into Usuario(DOCUMENTOIDENTIDAD,NOMBRE,CARGO,CONTRASENA,PERMISO)
values ('22323','asfa','Administrador','123456','0')
RETURNING ID INTO :temp
I have the corresponding trigger and Seq to generate the table autoincrement id.
Use CallableStatement and register the OUT parameter.
This is an excellent opportunity to register the IN parameters too.
String mySql = "DECLARE x NUMBER; BEGIN "
+ " insert into Usuario(DOCUMENTOIDENTIDAD,NOMBRE,CARGO,CONTRASENA,PERMISO) "
+ " values (?,?,?,?,?) "
+ " RETURNING ID INTO x;"
+ " ? := x;"
+ "END; ";
CallableStatement cal = conn.prepareCall(mySql);
cal.setString(1, "22323");
cal.setString(2, "asfa");
cal.setString(3, "Administrador");
cal.setString(4, "123456");
cal.setString(5, "0");
cal.registerOutParameter(6, java.sql.Types.INTEGER);
cal.executeQuery();
Integer newId = cal.getInt(6);
you are attempting to use a bind variable (:i) that is not bound to a value.
I want to ask for help my code that will find relevant name from database according to id number.
My code find the name that i try to find.
BUT i want to send an error message when the program can not find ID number.
I tried many ways but always when it couldnt find ID number, it said build succesfull and show no error just quitted the program.
Thanks for your help.
public void search(String ID) throws SQLException {
Statement mystate = con.createStatement();
String sql = "SELECT*FROM users" +
" WHERE id LIKE " + ID;
ResultSet rs = mystate.executeQuery(sql);
while (rs.next()) {
System.out.println("Your Name is " + rs.getString("name"));
}
}
Two big issues with your code:
You don't put SQL quotes around ID, so it looks like a keyword or identifer to the SQL parser
It's wide open to SQL-injection attacks (see below)
You want to use a PreparedStatement, which deals with both of those for you. Then just use a flag for whether you saw anything:
public void search(String ID) throws SQLException {
boolean sawOne = false;
PreparedStatement mystate = con.prepareStatement(
"SELECT * FROM users WHERE id LIKE ?"
);
mystate.setString(1, ID);
ResultSet rs = mystate.executeQuery(mystate);
while (rs.next()) {
sawOne = true;
System.out.println("Your Name is " + rs.getString("name"));
}
if (!sawOne) {
System.out.println("...");
}
}
I'm assuming ID already has a wildcard on it (or that you really don't want one).
Or if you know there will be only one match, or you only want one match even if there's more than one, you can add a
mystate.setMaxRows(1);
...before executeQuery(), and then just use if/else, no need for the flag:
if (rs.next()) {
System.out.println("Your Name is " + rs.getString("name"));
} else {
System.out.println("...");
}
Obligatory SQL-injection link: http://bobby-tables.com/
And cartoon:
public void search(String ID) throws SQLException {
Statement mystate = con.createStatement();
String sql = "SELECT*FROM users" +
" WHERE id LIKE " + ID;
ResultSet rs = mystate.executeQuery(sql);
if(rs.next()) {
System.out.println("Your Name is " + rs.getString("name"));
}
else
{
System.out.println("Id not found");
}
}
I've got the following code in my app
String sql = "SELECT colA, colB, colC " +
"FROM " + tblName + " WHERE UserId = " + userId +
" AND InsertTimestamp BETWEEN " + lastDate +
" AND " + DataProcessor.TODAY + " ORDER BY UserId, Occurred";
try{
if(null == conn)
openDatabaseConnection();
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery(); <------- this is the line which throws the SQL exception
retArray = this.getArrayListFromResultSet(rs);
}catch(SQLException sqle){
JSONObject parms = new JSONObject();
eh.processSQLException(methodName, sqle, sql, parms);
}
So when I run my app in the debugger, I get this exception message
com.mysql.jdbc.exceptions.jdbc4.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 '00:00:00.0 AND 2014-08-20 00:00:00.0 ORDER BY UserId, Occurred' at line 1
I'm reasonably certain that there's simple and reasonable solution to this, but I have not been able to find it.
I've tried looking in the MySQL manual for a solution or a different format.
I've tried running my timestamps through a TIMESTAMP() functino and a DATE() function in the SQL, neither of which helped.
I pulled the fully formed SQL out of the Java code and ran it in MySQL Workbench with no issues, what-so-ever. So now I'm looking to the experts for help.
Dates in SQL must be enclosed within single quotes like strings.
As you're using a prepared statemtent, why you don't use '?' and stmt.setDate(...)?
String sql = "SELECT colA, colB, colC " +
"FROM " + tblName + " WHERE UserId = ?" +
" AND InsertTimestamp BETWEEN ?" +
" AND ? ORDER BY UserId, Occurred";
try {
if(null == conn) {
openDatabaseConnection();
}
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, userId);
stmt.setDate(2, lastDate);
stmt.setDate(3, DataProcessor.TODAY);
ResultSet rs = stmt.executeQuery();
retArray = this.getArrayListFromResultSet(rs);
} catch(SQLException sqle) {
JSONObject parms = new JSONObject();
eh.processSQLException(methodName, sqle, sql, parms);
}
Anyway, I think you are setting the dates in the opposite order. You should put first 'today' then lastDate. Although I don't know your constraints...
m trying to loop through 3 resultsets and compare their values. bt its throwing this exception...could someone help me on where am going through?
here is the piece of code:
java.lang.Object[] reconciledPaymentDetails = null;
java.util.Vector shiftsVector = new java.util.Vector(1, 1);
String status = "";
try {
Class.forName("org.postgresql.Driver");
}
catch (ClassNotFoundException ex) {
Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
}
try {
connDB = DriverManager.getConnection("jdbc:postgresql://" + hostName + ":" + portNumber + "/" + dbName, userName, password);
System.out.println("Connection established : [" + connDB.toString() + "]");
java.sql.Statement pstmt = connDB.createStatement();
java.sql.Statement pstmtShifts = connDB.createStatement();
java.sql.ResultSet rset = pstmt.executeQuery("SELECT DISTINCT payment_mode,transaction_type, credit FROM ac_cash_collection WHERE shift_no = '" + shiftNumber + "'");
while (rset.next()) {
java.sql.ResultSet rsetShifts = pstmtShifts.executeQuery("SELECT DISTINCT amount, shift_amount FROM ac_shift_collections WHERE shift_no = '" + shiftNumber + "' AND pay_mode ilike '"+rset.getString(1) +"'");
while (rsetShifts.next()) {
java.sql.ResultSet rset2 = pstmt.executeQuery("select debit from ac_cash_book where shift_no='"+shiftNumber+"'");
while (rset2.next()){
double debit =rset2.getDouble("debit");
if((rset2.getDouble("debit")<=0 ))
status = "no_banked";
else if((rset2.getDouble("debit")==rsetShifts.getDouble("amount"))
&& (rsetShifts.getDouble("amount"))< rsetShifts.getDouble("shift_amount"))
status= "BntClosed";
else if (rset2.getDouble(1)==rsetShifts.getDouble("shift_amount"))
status ="bClosed";
shiftsVector.addElement(rset.getString(1)+":"+rsetShifts.getString(1)+":"+status);
}
}
}
The documentation provides a clear explanation of this:
By default, only one ResultSet object per Statement object can be open
at the same time. Therefore, if the reading of one ResultSet object is
interleaved with the reading of another, each must have been generated
by different Statement objects. All execution methods in the Statement
interface implicitly close a statment's current ResultSet object if an
open one exists.
So your options would be:
Use a different Statement instance for each query.
Collect all the results from each ResultSet (i.e. into a Set or a List) before moving on to the next one, and then run the comparison on the collected results instead of directly on the result-sets.