我正在尝试在数据库中保存文件。我能够使用SQL保存它完全正常。我用SQL避免的是直接在代码中提供密码,以便我考虑使用本机查询。我不确定我是否仍然可以使用SQL而不直接在代码中提供密码和用户名.SQL的代码如下
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/mydb", "postgres",
"postgres");
System.out.println("......Now attempting to insert the record.....");
// String matid = "007N00030000001";
File file = new File("C://JavaWorkspace/pdf-sample.pdf");
FileInputStream fis = new FileInputStream(file);
PreparedStatement ps = connection.prepareStatement("INSERT INTO cli.documents VALUES (?,?,?,?)");
ps.setBinaryStream(1, fis, (int)file.length());
ps.setString(2, "1");
ps.setString(3, file.getName());
ps.setString(4,matid);
ps.executeUpdate();
ps.close();
fis.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
如果使用本机查询,我无法看到任何可以使用的方法而不是 ps.setBinaryStream(1,fis,(int)file.length()); 只有setParameter 以下是我尝试使用原生查询
Query query = entityManager.createNativeQuery("INSERT INTO cli.documents (matid, doctype,upload,docfile) " +
" VALUES(?,?,?,?)");
EntityManagerFactory emfactory=Persistence.createEntityManagerFactory( "junit" );
EntityManager em = emfactory.createEntityManager( ); //= null;
EntityTransaction et = em.getTransaction();
et.begin();
em.createNativeQuery("INSERT INTO cli.documents (matid, doctype,upload,docfile) " + " VALUES(?,?,?,?)")
.setParameter(1,matid)
.setParameter(2, "1")
.setParameter(3, file.getName())
.setParameter(4, (int)file.length());
//.setBinaryStream(4, fis, (int)file.length())
// em.executeUpdate()
et.commit();