How to use setCharacterStream to update Clob in Oracle? - java

When I used the follow snippets to update Oracle Clob:
String toBeUpdated = ""
StringReader reader = new StringReader(toBeUpdated);
pStmt.setCharacterStream(parameterIndex,reader , toBeUpdated.length());
When the length of string "toBeUpdated" is a little bit bigger(general more than 5000) and a value had been ready stored into db, it was without any exceptions and the expected value was returned in method executeUpdate() when I ran the above codes. but the stranger probelm is that I checked DB and found the column was null.(it should be updated with new value).
it did not happened every time but a little bit randomly.
I tried use pStmt.setString() instead of pStmt.setCharacterStream everything was going to be fine. as far as I know setString is limited of maximize string size(63000) it cannot be proposed solution.
Is anybody can light me or experienced this?

Oracle provide Classes for store CLOB from strings. I have use the following code and it works fine:
long id = ...
String content = ... // CLOB content
try {
Class.forName ("oracle.jdbc.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:#MY_SERVER:1521:MY_DB", "user", "pass");
String query = "UPDATE MY_TABLE SET MY_CLOB_COLUMN = ? WHERE ID = ? ";
OraclePreparedStatement opstmt = (OraclePreparedStatement)conn.prepareStatement(query);
opstmt.setStringForClob(1, content);
opstmt.setLong(2, id);
int result = opstmt.executeUpdate();
System.out.println("Resultado para : " + tabla + " - " + columna + " - " + id + ":" + result);
} catch (SQLException ex) {
//Log here
} catch (ClassNotFoundException ex) {
//Log here
}

Related

Problem with Update query in Mysql with JDBC

see the screenshots
see the 2nd screenshot
see the 3rd screenshot
Okay so I am building a project on java and mysql, I am stuck at this point that I have to update a data which is in MySql but from my java gui application, I've executed that update command from MySql command line client
update user set bldu = 50 where userid = 1001;
and it's working perfectly fine there but from my java application on clicking on assigned jbutton it says:
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 'userid= 1001' at line 1
Please help me..!
In your first screenshot you must add a space before WHERE clause:
String query = "UPDATE user SET bdlu = " + bldut + "WHERE userid = " + uid + ";";
So your query will be interpretated as:
UPDATE user SET bdlu = 50WHERE userid = 1001
So you'll raise a syntax error.
Then you'll have the following query:
String query = "UPDATE user SET bdlu = " + bldut + " WHERE userid = " + uid + ";";
String query = "update user SET bldu = " + bldut + " WHERE userid = " + uid + ";";
use this one instead of your old query may be it is helpful for you.
Try this snippet in your code.
String query = "update user SET bldu = " + bldut + " WHERE userid = " + uid + ";";
Statement = con.prepareStatement(query);
Statement.executeUpdate();
by looking at your code you cannot store results of update query in resultSet the executeUpdate() only return 0 or 1 for success and failure of Update.
Okay i guys i have figured out something that it is working i mean this program is updating the data stored in mysql from netbeans via jdbc but it won't stop showing that error message like:
"Can not issue data manipulation statements with executeQuery()"
everytime i click one that assigned jButton..! but i checked the database the value i want to change is being changed but then why it is showing this error..?
Please use this code in your java file, do changes according to your file. your issue is you are using the same query in a result set that already uses for the update
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/bdb", "root", "root");
try {
String query = "update user SET bldu = " + bldut+ " WHERE userid = " + uid + ";";
// create the java mysql update preparedstatement
Class.forName("com.mysql.jdbc.Driver").newInstance();
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.executeUpdate();
query = "select * from user WHERE userid = " + uid +";";
ResultSet rs = stmt.executeQuery(query);
// STEP 5: Extract data from result set
while (rs.next()) {
// Retrieve by column name
String userid = rs.getString("userid");
String userfname = rs.getString("userfname");
// all your column
// Display values
System.out.print("userid: " + userid);
}
// STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
} finally {
// finally block used to close resources
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}// end finally try
}// end try

SQL Query In Java + Oracle

I'm really struggling to get this SQL into my head while using java.
My problem is: I want to use a variable in my sql Query, and i cant seem to get it working, it catches the correct value(i'm showing it on a label), But it doesnt show any records, yet, if i replace the variable for a '5', it shows me the correct record...
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = MySqlConnect.ConnectDb();
int idaca = Integer.parseInt(idhist.getText());
String query1 = "SELECT t.nome, h.Valor_Atual, h.Valor_Antigo, a.nome
FROM Tecnologias t, Historico h, Academista a
WHERE h.Id_Academista = a.Id_Academista AND a.Id_Academista = "+idaca+" AND h.Id_Tecnologia = t.Id_Tecnologia
AND (h.Valor_Atual || h.Valor_Antigo || t.nome) LIKE '%" + ValToSearch + "%'";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query1);
historico history;
while (rs.next()) {
history = new historico(rs.getString("Nome"), rs.getInt("Valor_Antigo"),
rs.getInt("Valor_Atual"), rs.getString("Nome"));
historicoList.add(history);
} //END WHILE
} //END TRY
catch (Exception e) {
JOptionPane.showInputDialog(null, e);
}//END CATCH
Thats my code so far... The ValToSearch is working fine, tho...
Thank you in advance! Cheers
Put an space before AND h.Id_Tecnologia. That should solve your problem.
You are not afraid that in ValToSearch you get something like ' OR 1 IN (DELETE * FROM Tecnologias )?
Use parametr escaping or better some query builder

Getting JdbcBatchUpdateException while testing with EmbeddedDatabase H2

I get strange exception trying to test my code using EmbeddedDatabase H2:
java.lang.RuntimeException:
java.lang.RuntimeException: org.h2.jdbc.JdbcBatchUpdateException: Timeout trying to lock table "CO_SCENARIO_1"; SQL statement:
UPDATE CO_SCENARIO_1 SET VALUE = ? WHERE ATTRIBUTE = ? AND MODIFIER = ? [50200-156]
at de.telekom.skses.test.dao.DatabaseFileConverterTest.fromFile(DatabaseFileConverterTest.java:99)
This is part of code I'm trying to test:
case "overriddenVariables.txt": {
try (Scanner sc = new Scanner(bOut.toString())) {
try (Connection con = dataSource.getConnection()) {
String aQuery = "UPDATE $tableName SET VALUE = ? WHERE ATTRIBUTE = ? AND MODIFIER = ?";
String line = "";
if (sc.hasNext()) {
line = sc.nextLine();
}
while (sc.hasNext()) {
if (line.startsWith("+")) {
String setting = line.substring(1);
try (PreparedStatement ps = con.prepareStatement(aQuery.replace("$tableName", setting))) {
while (sc.hasNext() && !(line = sc.nextLine()).startsWith("+")) {
int del1 = line.indexOf(":");
int del2 = line.indexOf(':', del1 + 1);
String attr = line.substring(0, del1);
String modifier = line.substring(del1 + 1, del2);
String value = line.substring(del2 + 1, line.length());
Clob myClob = con.createClob();
myClob.setString(1, value);
ps.setClob(1, myClob);
ps.setString(2, attr);
ps.setString(3, modifier);
ps.addBatch();
}
ps.executeBatch();
}
}
}
} catch (SQLException e) {
logger.error("Error", e);
throw new RuntimeException(e);
}
} catch (Exception ex) {
logger.error("Error", ex);
throw new RuntimeException(ex);
}
break;
}
StackOverflow says that I should set lock timeout, but I didn't find how to set it for EmbeddedDatabase. Also, in previous version I opened new PreparedStatement for each query and new Connection for each PreparedStatement, everything worked well, and I can't understand why it doesn't now. Could you please explain what I have to do to make it work again?
Sorry if something is incorrect, I'm new to Java EE.
As I remember using H2 in embedded mode, it has problems with concurrency. this is probably why you get the timeout for the lock on the table, since the table is still updated from your last batch when you try to execute the next one. When closing connection and preparedStatement every single time the execution time is way shorter, so you won't get the timeout.
Have you tried adding to the DatabaseURL ;MVCC=true as stated in this post? If this won't solve the problem, is it really necessary to use batches for your update?
EDIT: the post i linked before, links to the h2 website where you can find a description on how to change the lock timeout by adding ;LOCK_TIMEOUT=10000 to your databse URL. This would change it to 10 seconds, standard is 1 second

Android + Java + SQLite error reading TEXT field

When i save this string to a database:
# there is a hole.
when reading it back i get:
# there is a hol
Notice the missing last to characters: e.
if i try to save:
# theres a hole.
I correctly read back the string. Since the error depends on the lenght of the string, i think it might have something to do with unicode... but i am not sure.
Anybody knows what is going on? Here is the code i use to save the string to database:
lQuery = "UPDATE notices SET note='# there is a hole.' where id=3";
SQLiteDatabase mdb = (SQLiteDatabase) DBconn;
try {
mdb.execSQL(lQuery);
} catch (Exception ee) {
DBlasterr = ee.getMessage();
};
And here is how i am retrieving the string:
lQuery = "SELECT * FROM notices where id=3";
try {
SQLiteDatabase mydb = (SQLiteDatabase) DBconn;
rs = mydb.rawQuery(lQuery, null);
rs.moveToFirst();
Log.d("======", "returned: " + rs.getString(rs.getColumnIndex("note")));
} catch (Exception ee) {
DBlasterr = ee.getMessage();
}

SQL command not properly ended with select

I'm working with Oracle SQL Developer with a Java application. I want to ask to the DB this query:
select * from vocabolario, vocaboli_help where verbo=1 and
vocabolario.id = vocaboli_help.id and vocaboli_help.usato = 0
The query works when I run it from SQL developer, but when run it from Eclipse with the stmt.executeQuery(string), where stmt is a Statement object, it throws the following exception: SQL command not properly ended.
I put also a semicolon at the end of the string, but it doesn't work.
I used the stmt.executeQuery(string) with other queries and in those cases there were no problems. The only difference I can see is that in this case I have where condition in AND.
Java code :
private final static String NOME_DATABASE = "VOCABOLARIO", NOME_DATABASE_HELP ="VOCABOLI_HELP";
String type ="verbo";
String query = "SELECT * FROM " + NOME_DATABASE + ", " + NOME_DATABASE_HELP +" WHERE " + type + " = 1 " +
"AND " + NOME_DATABASE +".ID = " + NOME_DATABASE_HELP +".ID AND "+NOME_DATABASE_HELP+".USATO = 0";
System.out.println(query);
int cont = 0;
String result="";
try {
ResultSet res = statement.executeQuery(query);
while(res.next()) {
String cod = res.getString("ID").trim();
String voc = res.getString("VOCABOLO").trim();
String trad = res.getString("TRADUZIONE").trim();
if(cont == n)
result = cod + "," + voc + "," + trad;
cont++;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
`
select * from vocabolario vo
left join vocaboli_help voh
on vo.id= voh.id
where v.verbo=1 AND voh.usato=0
You just need a simple join.
VOCABOLI_HELP or vocabolario_help your code and your post different
Thank you all, the problem was in the name of the second table, but I think it depends on Java code sintax, as #are suggested.
I updated the code:
private static final String NOME_DATABASE_HELP = "VOCABOLIHELP"
I also modified the table name in the DB and now it works. I think there are issues with the underscore in the name (the problem is only in Java as I said), I don't know why.

Categories

Resources