I am trying to insert data into sqlite table but it is giving me exception no such exception.please check my code and let me what changes should i make?
static Connection con;
public static Connection getConnection()
{
try
{
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:/home/zack/another.db");
con.setAutoCommit(false);
System.out.println("Opened database successfully");
}
catch(Exception e)
{
System.out.println("EXCEPTION IN :: SqliteCon:"+e.getMessage());
}
return con;
}
and here is my insert command file.
public String execute()
{
BufferedReader br;
try {
Connection con = SqliteCon.getConnection();
Statement stmt = con.createStatement();
br = new BufferedReader(new FileReader(
"/home/Zack/Desktop/session.csv"));
String line;
while ((line = br.readLine()) != null) {
String[] value = line.split(","); // your seperator
stmt.executeUpdate("INSERT into sessionTab values('jack','pass','NYC'")
//later i will insert values from CSV file
br.close();
}
}
catch (Exception e) {
System.out.println("Exception in UploadData class");
e.printStackTrace();
}
return SUCCESS;
}
I also added jar file to WEB-INF/lib/ of my project
finally solved this issue!!!switched from sqliteman to Firefox sqlite plugin and changed extension of db file from .db to .sqlite.
Related
I am trying to read a pdf file that has been stored in a table on SQLite database. when I run the Code it says ' Resultset is closed'.
public void syllabusAttach(){
String selectSQL = "SELECT Image_Reg FROM "+getRegulation()+" WHERE SubjectCode="+getSubCode()+"";
ResultSet rs = null;
FileOutputStream fos = null;
Connection conn = null;
Statement stmt = null;
try {
conn = connect();
stmt = conn.createStatement();
rs = stmt.executeQuery(selectSQL);
// write binary stream into file
InputStream is =rs.getBinaryStream("Image_Reg");
File file = new File("syllabus_"+getRegulation()+".pdf");
OutputStream os = new FileOutputStream(file);
System.out.println("Writing BLOB to file " + file.getAbsolutePath());
byte[] content = new byte[1024];
int size = 0;
while((size = is.read(content)) !=-1){
os.write(content,0,size);
}
} catch (SQLException | IOException e) {
System.out.println(e.getMessage());
} finally {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
if (fos != null) {
fos.close();
}
} catch (SQLException | IOException e) {
System.out.println(e.getMessage());
}
}
}
write binary stream into file
File file = new File("syllabus_"+getRegulation()+".pdf");
fos = new FileOutputStream(file);
System.out.println("Writing BLOB to file " + file.getAbsolutePath());
while (rs.next()) {
InputStream input = rs.getBinaryStream("Image_Reg");
byte[] buffer = new byte[1024];
while (input.read(buffer) > 0) {
fos.write(buffer);
}
}
When I did the above changes to the code, I could see that the files are being generated but when I open them it says "this file cannot be opened"
I found that the getSubCode() in the SQl query is not returning a the desired string which is leading to the error.
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.
I've got an annoying bug in Java. I'm connecting to a MySQL database and using Tomcat in Eclipse. It works brilliantly, but only the first time around. If I reload the page or run the page again, I get a com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.
This is my code:
Connection conn = null;
String returnString = null;
Response response = null;
ResultSet rs = null;
try {
System.out.println("Trying to connect");
conn = DbUtil.getConnection(); // Connect to the database
System.out.println("Okay, connected");
query = conn.prepareStatement("SELECT host_firstname FROM host"); //Crashes at this line!
rs = query.executeQuery();
ConvertToJson jsonConverter = new ConvertToJson();
JSONArray jsonArray = new JSONArray();
jsonArray = jsonConverter.convertToJsonArray(rs);
returnString = jsonArray.toString();
response = Response.ok(returnString).build();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("hello!!!!");
}
finally {
if (rs != null){
rs.close();
}
if (query != null) {
query.close();
}
if (conn != null) {
conn.close();
}
}
return response;
I've seen everywhere I've Googled that I have to close the result set, the prepared statement and the connection (in that order) but once I've closed the connection, I can't reopen it.
This is my DbUtil class:
private static Connection connection = null;
public static Connection getConnection() {
if (connection != null) {
return connection;
}
else {
try {
Properties prop = new Properties();
InputStream inputStream = DbUtil.class.getClassLoader().getResourceAsStream("/db.properties");
prop.load(inputStream);
String driver = prop.getProperty("driver");
String url = prop.getProperty("url");
String user = prop.getProperty("user");
String password = prop.getProperty("password");
Class.forName(driver);
connection = DriverManager.getConnection(url, user, password);
}
catch (IOException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return connection;
}
Any idea what is causing this problem?
Thanks
Omar :)
This answer is just to get your code working. But the best way would be to configure a connection pool. You should look about it.
YOur condition is :
if (connection != null) {
return connection; It's returning a closed connection
}
Try changing it to:
if (connection != null && !connection.isClosed()) {
return connection;
}
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();
}
}
I wrote a java sever socket,it could connect postgresql and return values,but when I compile javac -deprecation SQLServer.java
And why warning cannot work?
It didn't have any error.How can I fix it?
SQLServer.java:66: warning: [deprecation] readLine() in DataInputStream has been deprecated
query = in.readLine();
^
1 warning
code:
import java.io.*;
import java.net.*;
import java.util.*;
import java.sql.*;
public class SQLServer extends Thread{
public static final int MYPORT = 6700;
ServerSocket listen_socket;
public SQLServer(){
try{
listen_socket = new ServerSocket (MYPORT);
}
catch(IOException e) {System.err.println(e);}
this.start();
}
public void run(){
try{
while(true)
{
Socket client_socket = listen_socket.accept();
SQLConnection c = new SQLConnection (client_socket);
}
}
catch(IOException e) {System.err.println(e);}
}
public static void main(String[] argv){
new SQLServer();
}
}
class SQLConnection extends Thread{
protected Socket client;
protected DataInputStream in;
protected PrintStream out;
protected String query;
public SQLConnection (Socket client_socket){
client = client_socket;
try{
in = new DataInputStream(client.getInputStream());
out = new PrintStream (client.getOutputStream());
}
catch(IOException e) {
System.err.println(e);
try {client.close();}
catch (IOException e2) {};
return;
}
this.start();
}
public void run(){
try{
query = in.readLine();
System.out.println("read query string <" + query + ">");
do_sql();
//out.println(d.toString());
}
catch (IOException e) {}
finally{
try {client.close();}
catch (IOException e) {};
}
}
public void do_sql(){
Connection con; // database connection object
Statement stmt; // SQL statement object
ResultSet rs; // SQL query results
ResultSetMetaData rsmd;
boolean more; // "more rows found" switch
String dsn = "jdbc:postgresql://localhost/postgres";
String user = "postgres";
String password = "123456";
String record;
int colcount, i;
try{
Class.forName ("org.postgresql.Driver");
con = DriverManager.getConnection(dsn, user, password);
stmt = con.createStatement();
rs = stmt.executeQuery(query);
more = rs.next();
if (!more) {
out.println("No rows found.");
return;
}
rsmd = rs.getMetaData();
colcount = rsmd.getColumnCount();
System.out.println(colcount + " columns in result set");
while (more) {
//build result string
record = "";
for (i=1; i <= colcount; i++){
record = record.concat(rs.getString(i) + " ");
}
out.println(record);
System.out.println(record);
more = rs.next();
}
rs.close();
stmt.close();
con.commit();
con.close();
}
catch (Exception e)
{
System.out.println("Exception occurred" + e.toString());
}
}
}
From DataInputStream#readLine javadoc:
Deprecated. This method does not properly convert bytes to characters. As of JDK 1.1, the preferred way to read lines of text is via the BufferedReader.readLine() method. Programs that use the DataInputStream class to read lines can be converted to use the BufferedReader class by replacing code of the form:
DataInputStream d = new DataInputStream(in);
with:
BufferedReader d = new BufferedReader(new InputStreamReader(in));
The method was deprecated because Streams are meant to be treating bytes, to treat text we have since a long time Readers & Writers as they offer the functionality to use encodings.
if you want text to be read try wrapping your stream into a reader
BufferedReader r = new BufferedReader(new InputStreamreader(your data stream, optional encoding parameter like "UTF-8"))
r.readLine();
This is what the Java API says:
Deprecated.
This method does not properly convert bytes to characters. As of JDK 1.1, the preferred way to read lines of text is via the BufferedReader.readLine() method. Programs that use the DataInputStream class to read lines can be converted to use the BufferedReader class by replacing code of the form:
DataInputStream d = new DataInputStream(in);
with:
BufferedReader d
= new BufferedReader(new InputStreamReader(in));