本文介绍了将Java对象保存到PostgreSQL问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用以下代码将对象保存在postgre列(字节)中:
I'm trying to save an object in a postgre column(bytea) with the following code:
Utilisateur utilisateur = new Utilisateur("aa","aa","aa",10,"aaammm",12,Role.ADMINISTRATEUR); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(utilisateur); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); Connection connection = null; PreparedStatement preparedStatement = null; connection = Connect(); String SOME_SQL= "INSERT INTO test (id, objet) VALUES( ?, ?)"; preparedStatement = connection.prepareStatement(SOME_SQL); preparedStatement.setBinaryStream(2, bais); preparedStatement.setInt(1, 11); preparedStatement.executeUpdate(); preparedStatement.close();但是我得到这个证据:
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:532) at org.eclipse.ve.internal.java.vce.launcher.remotevm.JavaBeansLauncher.main(JavaBeansLauncher.java:86) Caused by: org.postgresql.util.PSQLException: Function org.postgresql.jdbc4.Jdbc4PreparedStatement.setBinaryStream(int, InputStream) is not implemented. at org.postgresql.Driver.notImplemented(Driver.java:753) at org.postgresql.jdbc4.AbstractJdbc4Statement.setBinaryStream(AbstractJdbc4Statement.java:129) at com.grst.connector.SerializeToDatabase.<init>(SerializeToDatabase.java:35) ... 5 more我想在jdbc4中没有实现setBinaryStream(int,InputStream).还有其他方法吗?
i guess, that there is no setBinaryStream(int , InputStream) implemented in the jdbc4. There is any other way to do so ?
推荐答案您需要使用setBinaryStream(int, InputStream, int),其中第三个参数表示输入流的长度(以字节为单位).
You need to use setBinaryStream(int, InputStream, int) where the third parameter denotes the length of the input stream in bytes.
因此,在您的情况下,它将类似于:
So in your case this would be something like:
byte[] data = baos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(data); .. .. preparedStatement.setBinaryStream(2, bais, data.length);更多推荐
将Java对象保存到PostgreSQL问题
发布评论