Cachedrowset, JDBC and SQL server 2008 insert image problem - java

I'm trying to insert an image file (.png,200KB) into Sql sever (columb type varbinary(max)) via jdbc type 4 (microsoft jdbc 3.0), here is my code:
crsi.moveToInsertRow();
crsi.updateInt(1, Integer.parseInt(txt_TargetID.getText()));
crsi.updateBinaryStream(2, fis,f.length());
crsi.updateString(3, txt_Name.getText());
crsi.updateString(4, btng_Gender.getSelection().getActionCommand());
crsi.updateString(5, dpk_Birthdate.getSelectedDateAsText());
crsi.updateString(6, txt_IdenNo.getText());
crsi.updateString(7, dpk_RecordDate.getSelectedDateAsText());
crsi.insertRow();
crsi.moveToCurrentRow();
crsi.acceptChanges();
crsi is cachedrowsetimpl object,fis is Fileinputstream object
Every going right, the columns get inserted, except the image column remain NULL.
What going wrong?

Ok, i've solved this question. I should have enabled FILESTREAM in SQL server , also must have a Filestream group database,in which must have rowguiid and uniqueindentifier column.
Furthermore i can't use cachedrowset to upload filestream but i must use preparestatement to upload filestream.(cachedrowset will cause sync conflict)

Related

Connection closed when trying to read an oracle Clob returned from procedure

I have an Oracle procedure with an input Clob and returns an output Clob.
When i'm trying to recover the value, i reach the object, if i try to read the toString fro the object, i take the "oracle.sql.CLOB#625a8a83" . But when i want to read the object, in anyways i tryed, allways get a connection closed exception.
in my code:
MapSqlParameterSource parametros = new MapSqlParameterSource();
// setting input parameter
parametros.addValue("PE_IN", new SqlLobValue("IN DATA CLOB", new DefaultLobHandler()),
Types.CLOB);
// Executing call
Map<String, Object> out = jdbcCall.execute(parametros);
salida.setDatosRespuesta(out.get("PS_OUT").toString());
if i change the last line for this:
Clob clob = (Clob) out.get("PS_OUT");
long len = clob.length();
String rtnXml = clob.getSubString(1, (int) len);
i get the connection close error. I tryed in several ways and i can't solve this problem. Any ideas?
I think yo are using the SimpleJdbcCall of the spring framework. If so the database configuration are the default configurations for the oracle driver, you need to increase the time out for the reading of the values for the connection. Check the DatabaseMetaData documentation, also check the OracleConnection properies CONNECTION_PROPERTY_THIN_READ_TIMEOUT_DEFAULT. This happends because you are reading a large data from the database remember that de CLOB can have until 4gb of data
You need to keep in mind that is this process is very common in your application you need to consider the quantity of the connections to the database in order to have always enable connections to your database to guarantee your application availability
Regarding the out.get("PS_OUT").toString() this basically only show the hash that represents your object that the reason beacause why that line works fine

Store base64 encoded PDF document to Sybase

I need to store base64 encoded document in Sybase database via stored procedure. I use JTDS driver.
As long as I am not trying to store my PDF document everything is fine. However as soon I attempt to path encoded string. I get the following error
java.sql.SQLException: Sybase does not support char parameters > 255
bytes.
Here is the code
conn.setAutoCommit(false);
cs = conn.prepareCall("{call sp_save_pdf (?,?,?,?)}");
cs.setString(++i, id);
cs.setString(++i, source);
cs.setString(++i, base64EncodedDocument);
cs.registerOutParameter(++i, java.sql.Types.INTEGER);
cs.execute();
When Sybase Developers execute this procedure but they use JConnect driver. Here is my question does JTDS driver not support usage of long strings and I need to use JConnect or do I miss something in my code?
Thanks
Issue was with JTDS driver as soon as I switched to JConnect driver everything began to work as expected.

hbm2ddl.auto is not creating schema automatically when set to create [duplicate]

I am getting below exception, when trying to insert a batch of rows to an existing table
ORA-00942: table or view does not exist
I can confirm that the table exists in db and I can insert data to that table using oracle
sql developer. But when I try to insert rows using preparedstatement in java, its throwing table does not exist error.
Please find the stack trace of error below
java.sql.SQLException: ORA-00942: table or view does not exist
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:289)
at oracle.jdbc.ttc7.Oall7.receive(Oall7.java:573)
at oracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1889)
at oracle.jdbc.ttc7.TTC7Protocol.parseExecuteFetch(TTC7Protocol.java:1093)
at oracle.jdbc.driver.OracleStatement.executeNonQuery(OracleStatement.java:2047)
at oracle.jdbc.driver.OracleStatement.doExecuteOther(OracleStatement.java:1940)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout>>(OracleStatement.java:2709)
at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:589)
at quotecopy.DbConnection.insertIntoDestinationDb(DbConnection.java:591)
at quotecopy.QuoteCopier.main(QuoteCopier.java:72)
Can anyone suggest the reasons for this error ?
Update : Issue solved
There was no problem with my database connection properties or with my table or view name. The solution to the problem was very strange. One of the columns that I was trying insert was of Clob type. As I had a lot of trouble handling clob data in oracle db before, gave a try by replacing the clob setter with a temporary string setter and the same code executed with out any problems and all the rows were correctly inserted!!!.
ie. peparedstatement.setClob(columnIndex, clob)
was replaced with
peparedstatement.setString(columnIndex, "String")
Why an error table or view does exist error was throws for error in inserting clob data. Could anyone of you please explain ?
Thanks a lot for your answers and comments.
Oracle will also report this error if the table exists, but you don't have any privileges on it. So if you are sure that the table is there, check the grants.
There seems to be some issue with setCLOB() that causes an ORA-00942 under some circumstances when the target table does exist and is correctly privileged. I'm having this exact issue now, I can make the ORA-00942 go away by simply not binding the CLOB into the same table.
I've tried setClob() with a java.sql.Clob and setCLOB() with an oracle.jdbc.CLOB but with the same result.
As you say, if you bind as a string the problem goes away - but this then limits your data size to 4k.
From testing it seems to be triggered when a transaction is open on the session prior to binding the CLOB. I'll feed back when I've solved this...checking Oracle support.
There was no problem with my database connection properties or with my table or view name. The solution to the problem was very strange. One of the columns that I was trying insert was of Clob type. As I had a lot of trouble handling clob data in oracle db before, gave a try by replacing the clob setter with a temporary string setter and the same code executed with out any problems and all the rows were correctly inserted!!!.
ie. peparedstatement.setClob(columnIndex, clob)
was replaced with
peparedstatement.setString(columnIndex, "String")
#unbeli is right. Not having appropriate grants on a table will result in this error. For what it's worth, I recently experienced this. I was experiencing the exact problem that you described, I could execute insert statements through sql developer but would fail when using hibernate. I finally realized that my code was doing more than the obvious insert. Inserting into other tables that did not have appropriate grants. Adjusting grant privileges solved this for me.
Note: Don't have reputation to comment, otherwise this may have been a comment.
We experienced this issue on a BLOB column. Just in case anyone else lands on this question when encountering this error, here is how we resolved the issue:
We started out with this:
preparedStatement.setBlob(parameterIndex, resultSet.getBlob(columnName)); break;
We resolved the issue by changing that line to this:
java.sql.Blob blob = resultSet.getBlob(columnName);
if (blob != null) {
java.io.InputStream blobData = blob.getBinaryStream();
preparedStatement.setBinaryStream(parameterIndex, blobData);
} else {
preparedStatement.setBinaryStream(parameterIndex, null);
}
I found how to solve this problem without using JDBC's setString() method which limits the data to 4K.
What you need to do is to use preparedStatement.setClob(int parameterIndex, Reader reader). At least this is what that worked for me. Thought Oracle drivers converts data to character stream to insert, seems like not. Or something specific causing an error.
Using a characterStream seems to work for me. I am reading tables from one db and writing to another one using jdbc. And i was getting table not found error just like it is mentioned above. So this is how i solved the problem:
case Types.CLOB: //Using a switch statement for all columns, this is for CLOB columns
Clob clobData = resultSet.getClob(columnIndex); // The source db
if (clobData != null) {
preparedStatement.setClob(columnIndex, clobData.getCharacterStream());
} else {
preparedStatement.setClob(columnIndex, clobData);
}
clobData = null;
return;
All good now.
Is your script providing the schema name, or do you rely on the user logged into the database to select the default schema?
It might be that you do not name the schema and that you perform your batch with a system user instead of the schema user resulting in the wrong execution context for a script that would work fine if executed by the user that has the target schema set as default schema. Your best action would be to include the schema name in the insert statements:
INSERT INTO myschema.mytable (mycolums) VALUES ('myvalue')
update: Do you try to bind the table name as bound value in your prepared statement? That won't work.
It works for me:
Clob clob1;
while (rs.next()) {
rs.setString(1, rs.getString("FIELD_1"));
clob1 = rs.getClob("CLOB1");
if (clob1 != null) {
sta.setClob(2, clob1.getCharacterStream());
} else {
sta.setClob(2, clob1);
}
clob1 = null;
sta.setString(3, rs.getString("FIELD_3"));
}
Is it possible that you are doing INSERT for VARCHAR but doing an INSERT then an UPDATE for CLOB?
If so, you'll need to grant UPDATE permissions to the table in addition to INSERT.
See https://stackoverflow.com/a/64352414/1089967
Here I got the solution for the question. The problem is on glass fish if you are using it. When you create JNDI name make sure pool name is correct and pool name is the name of connection pool name that you are created.

Save unicode characters in DB using java

I need to save some uni-code characters in Sql server 2005 DB with JDBC, When i try to save "O’CON" into DB column having type NVarchar using a stored procedure it saves "O?CON" `(where ’ character is not `` or ')
I did some R&D and found that i need to add useUnicode=true&characterEncoding=UTF-8 some where in my DBcon.properties file that contains all the details of DB connection,
Can some one help me out where to add this into properties file or it i can add it at run time when i create a connection object.
Or if someone can help me how to save unicodes characters in DB using java.
Thanks.
To connect to database you use connect string specific to your database and driver.
I used MS MSQ long time ago but I remember that they had jtds driver. Connect string for such driver looks like:
jdbc:jtds:sqlserver://hostname:1433/my_database;useUnicode=true;characterEncoding=UTF-8
But from that time MS create their own JDBC driver and if you use it then I think you can add:
sendStringParametersAsUnicode=true
to your connect string. It is decribed at http://technet.microsoft.com/en-us/library/ms378988.aspx
In a case of problems show us your connect string and code where it is used.

Tomcat6 MySQL Unknown column in 'field list'"

I'm working in a RedHat with Tomcat6 and MySQL, and i'll apreciate your help with a problem, i have a servlet connected to my DB , well, I send a sql "String" to my servlet and the servlet executes this code, i'm printing my sql string, something like this
"INSERT INTO xsn_core_helix_streams_stats (timestamp,type,client,publish_time,connects,id_stream,server) VALUES('2013/02/11 16:23:27',null,null,null,'1','4',6);"
but i have receiving an Exception
"java.sql.SQLException: Unknown column 'server' in 'field list'"
and when i describe my table , i can see the column , and when i copy and paste in the console , i can see "Query OK, 1 row affected (0.03 sec)"
Why?
Despite the responses from #paulsm4 and #ilopezluna, SERVER is not a reserved word in MySQL. Cf. http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
I would therefore double-check that your table xsn_core_helix_streams_stats actually has a column named server.
For instance, try opening the MySQL client, ready the database, and run SHOW CREATE TABLE LIKE xsn_core_helix_streams_stats.
I can reproduce the error you report by creating a table without a column named server, and attempting the INSERT statement in your example.
My workbench mark the word "server", so maybe is a reserved word. Try to change the name of column in your table and query and try again
I solved the problem, tomcat6 backs my servlet configuration file (Servlet / META-INF / context.xml) and place it in / etc/tomcat6/Catalina/localhost, then the matter is that this file was not correct, greetings and thanks!!

Categories