I am trying to save a file in the database. I am able to save using SQL it works perfectly fine. What I am avoiding with SQL is providing password directly in the code that why I am considering using native query. I am unsure if I can still use SQL without providing password and username directly in the code.The code for the SQL is as below
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();
}
If using native query I cant see any method that I can use instead of
ps.setBinaryStream(1, fis, (int)file.length());
there is only setParameter
below is my attempt using native query
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();
Related
I cant print SQL table with JAVA. I think JDBC Connection is not a problem. How can I print table in console??
Connection conn = null;
Statement stmt = null;
String url = "jdbc:oracle:thin:#localhost:1521:orcl";
String user = "system";
String pwd = "SSTTaarr00119922";
ResultSet rs = null;
I did drivermanager getconnection.
System.out.println("start Connection");
try {
Class.forName("oracle.jdbc.OracleDriver");
conn = DriverManager.getConnection(url, user, pwd);
} catch (ClassNotFoundException e1) {
System.out.println("Error loading driver:" + e1.toString());
return;
} catch (Exception e2) {
System.out.println("Fail DB Connection:" + e2.toString());
return;
}
String sql = "SELECT * FROM dept";
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
System.out.println(sql);
while (rs.next()) {
String deptno = rs.getString(1);
String dname = rs.getString(2);
String Loc = rs.getString(3);
System.out.println(deptno + dname + Loc);
}
I cant print while func.
In your code, you are missing the catch in try---catch block. The code below is worked with SQL Server
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
System.out.println("start Connection");
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection("jdbc:sqlserver://localhost;databaseName=xxx;", "yyy", "zzz");
} catch (ClassNotFoundException e1) {
System.out.println("Error loading driver:" + e1.toString());
return;
} catch (Exception e2) {
System.out.println("Fail DB Connection:" + e2.toString());
return;
}
String sql = "SELECT * FROM [dbo].[User]";
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
System.out.println(sql);
while (rs.next()) {
String deptno = rs.getString(1);
String dname = rs.getString(2);
String Loc = rs.getString(3);
System.out.println(deptno + dname + Loc);
}
} catch (Exception e2) {
System.out.println("Fail DB Connection:" + e2.toString());
}
I have Spring Boot REST Application that runs on Azure on app service api-app.
I need to read access database files from this path on azure "D:\home\site\wwwroot\database>".
When I read a file from that location I need to delete them.
This is my code for read and delete file from azure, but when I go to KUDU Debug Console, file was not deleted.
public List<AccessFeedDTO> download(Long fileId) throws URISyntaxException, StorageException, IOException, SQLException{
if(fileId!=null){
File file = null;
try {
ImportFileFeedDTO importFileFeedDTO= importFileFeedService.getFeedFile(fileId);
storageAccount = CloudStorageAccount.parse(storageConnectionString);
CloudFileClient fileClient = storageAccount.createCloudFileClient();
CloudFileShare share = fileClient.getShareReference("spartanv3files");
CloudFileDirectory rootDir = share.getRootDirectoryReference();
CloudFile cloudFile = rootDir.getFileReference(importFileFeedDTO.getFile_uuid());
System.out.println(cloudFile.getName());
System.out.println(cloudFile.downloadText());
file = new File ("D:/home/database/"+importFileFeedDTO.getFile_uuid());
FileOutputStream fileOutputStream = new FileOutputStream(file);
cloudFile.download(fileOutputStream);
fileOutputStream.close();
System.gc();
List<AccessFeedDTO> accessFeedsDTOlist= accessFeedMapper.accessFeedEntitytolistofAccessFeedDTO(accessFeedRepository.getAllAccessFeeds(importFileFeedDTO.getFile_uuid()));
file.delete();
return accessFeedsDTOlist;
} catch (InvalidKeyException invalidKey) {
throw new RuntimeException(invalidKey.getMessage());
}finally{
file.delete();
}
}else{
throw new RuntimeException();
}
}
And this is the way how I set up a connection to that file (access database) on azure. I used UCanAccess to connect to temporary Access files for reading data.
public Connection getAccessFeedConnection(String fileName){
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
connection = DriverManager.getConnection("jdbc:ucanaccess://D:/home/database/"+fileName+";immediatelyReleaseResources=true");
return connection;
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
return connection;
}
}
And here is how I use connection to pic up parameters from access database
public List<AccessFeedEntity> getAllAccessFeeds(String dataBaseName) throws SQLException{
Connection connection = accessConfig.getAccessFeedConnection(dataBaseName);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM TBLFEEDS");
try {
List<AccessFeedEntity> listofaccessFeedEntity = new ArrayList<AccessFeedEntity>();
while(resultSet.next()){
AccessFeedEntity accessFeedEntity = new AccessFeedEntity();
accessFeedEntity.setFeedid(resultSet.getLong("ID"));
accessFeedEntity.setFeedname(resultSet.getString("NAME"));
listofaccessFeedEntity.add(accessFeedEntity);
}
connection.close();
statement.close();
resultSet.close();
return listofaccessFeedEntity;
} catch (SQLException e) {
connection.close();
statement.close();
resultSet.close();
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}finally{
try {
connection.close();
statement.close();
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
When I try to delete that file on Kudu Debug Console I get the following message "The process cannot access the file because it is being used by another process.
"
When I try this on localhost file is deleted. But on Azure doesn't work.
Where I went wrong and where I did not close the stream?
Or can someone help me to delete this file on other way?
Try stopping the app and deleting it from Kudu while the app is off.
In my application I'm using neo4j-community-2.3.0-M02 with neo4j-jdbc 2.3.2 . It creates large number of threads each should execute 3 or 4 cypher queries. To execute queries I use following method,
private ResultSet executeCypher(String queryString) throws Exception {
try {
String restUrl = getPropertiesCache().getCofigProperty("neo4j_url");
String driver = getPropertiesCache().getCofigProperty("neo4j_driver");
String userName = getPropertiesCache().getCofigProperty("neo4j_user");
String passWord = getPropertiesCache().getCofigProperty("neo4j_pwd");
Class.forName(driver);
try{
Neo4jConnection connection = (Neo4jConnection)
DriverManager.getConnection(restUrl, userName, passWord);
try {
PreparedStatement stmt = connection.prepareStatement(queryString);
try{
ResultSet rs = (ResultSet) stmt.executeQuery(queryString);
stmt.close();
connection.close();
return rs;
}catch (SQLException e){
e.printStackTrace();
} catch (NullPointerException e1){
e1.printStackTrace();
} catch (RuntimeException e2){
e2.printStackTrace();
}
if(!stmt.isClosed()){
stmt.close();
}
}catch (Exception e){
e.printStackTrace();
}
if(!connection.isClosed()){
connection.close();
}
}catch (Exception e){
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Which means I'm creating db connection for each cypher query. I think it's very bad idea because when creating large number of connections most of them start to be timeout. I think db connection pooling will help on this case or is there any better idea regarding this than connection pool?
If connection pooling solve this issue, please give an example of how to create db connection pool using neo4j jdbc driver.
The neo4j-jdbc 2.3X driver uses the REST API to connect to the database, basically they are http calls using Restlet API, so there is no connection being opened or closed when you create/close JDBC connections.
Im making a REST Api using JAX RS and Google Cloud Platform, however when i test the api I get HTTP204 no content returned, I think it could be to do with my database connection but no matter what I change it doesnt fix it
#Override
public Response getAllStaff() {
ArrayList<StaffInfo> staffArray = new ArrayList<>();
Response response = null;
String url = null;
try {
if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production) {
Class.forName("com.mysql.jdbc.GoogleDriver").newInstance();
url = "jdbc:google:mysql://{project-id}:staff-database/staffDatabase";
}
// Connection conn = DriverManager.getConnection(
// "jdbc:google:mysql://your-project-id:your-instance- name/database",
// "user", "password");
Connection conn = DriverManager.getConnection(url, "michael", "password");
Statement st = conn.createStatement();
String sql = ("SELECT * FROM StaffTable;");
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
staffArray.add(new StaffInfo(rs.getInt(0),
rs.getString(1),
rs.getString(2),
rs.getString(3),
rs.getString(4),
rs.getString(5)));
}
GenericEntity<ArrayList<StaffInfo>> entity =
new GenericEntity<ArrayList<StaffInfo>>(staffArray) {};
response = Response.ok(entity).build();
// response = Response.ok(entity, MediaType)
conn.close();
} catch (ClassNotFoundException e) {
// Could not find the database driver
} catch (SQLException e) {
// Could not connect to the database
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
I get no error messages just that there is no content returned
Here is what i see on cloud platform sql
and when i click on "staff-database"
Make sure the IP address of the machine from which you are making the call is authorized. You will find it in the "Access Control" tab of Cloud SQL.
I am trying to upload an image file with the code below, but the file is not being uploaded. The console still shows the message "1 Record Successfully Inserted."
Create table image
(
name varchar2(20),
photo blob
);
import java.sql.*;
import java.io.*;
public class ImageWriter {
static Connection connection = null;
static CallableStatement pstat = null;
static String connectionURL = null;
public static void main(String[] args) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe", "SYSTEM", "SYSTEM");
PreparedStatement pstat = connection.prepareStatement("insert into image(name,photo) values(?,?)");
FileInputStream fin = new FileInputStream("E:\\test.jpg");
pstat.setString(1, "ABC");
pstat.setBinaryStream(2, fin,fin.available());
int result = pstat.executeUpdate();
System.out.println(result + " Record Successfully Inserted");
connection.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
The above code works fine.
I dont know how you verified the contents of database.
Here is my code to verify the db(blob column): Try with this method. I used your code to insert the image and I could retrieve the image successfully. (note : file extension should be same)
public static void getPic() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:orcl", "sys as sysdba",
"Oracle123");
ResultSet rs = null;
Statement stmt = null;
oracle.sql.BLOB photo = null;
conn.setAutoCommit(false);
stmt = conn.createStatement();
String name="ABC";
rs = stmt.executeQuery("select photo from image where name = '" + name + "'" );
rs.next();
photo = ((OracleResultSet) rs).getBLOB(1);
File f = new File("E:/image2.jpg");
f.getParentFile().mkdirs();
f.createNewFile();
InputStream in = photo.getBinaryStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
OutputStream outputStream = new FileOutputStream(f);
int bufferSize = 1024;
int length = (int) photo.length();
byte[] buffer = new byte[bufferSize];
while((length = in.read(buffer)) != -1) {
out.write(buffer,0,length);
}
out.writeTo(outputStream);
System.out.println("Image Retrieved");
out.close();
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}