I have such a problem, I have a class for working with a database, but since I am not familiar with java, I have a problem with adding an image to the database. If in c# I would simply create an array of bytes and add it to the line, then here I don’t know how this can be implemented.
Example create sql line in c#
string sqlLine = $"insert .... values({bytes})"
Class DataBase in java
Method command is responsible for sending the command to the database, the cmd argument is just the same sql query.
package Models;
import java.sql.*;
import java.util.ArrayList;
public class DataBase {
// url connection
private final String url = "jdbc:sqlite:----";
private Connection connection = null;
private ResultSet resultSet = null;
private Statement statement = null;
private ArrayList<ArrayList<String>> info = null;
/*
* Database connection
* Param = none
* Return = none
* */
private void connectionOpen()
{
try {
connection = DriverManager.getConnection(url);
}
catch (SQLException ex){
connection = null;
}
}
/*
* Closing the database connection
* Param - None
* Return - None
* */
private void connectionClose() throws SQLException
{
if(connection != null) {
connection.close();
connection = null;
}
}
public Connection getConnection() { return connection; }
private void writeDataToList() throws SQLException {
info = new ArrayList<ArrayList<String>>();
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
final int ColumnCount = resultSetMetaData.getColumnCount();
while (resultSet.next()) {
ArrayList<String> temp = new ArrayList<>();
for (int j = 1; j <= ColumnCount; j++)
temp.add(resultSet.getString(j));
info.add(temp);
}
}
/*
* Sending sql query to database
* Param - cmd (sql request)
* Return - ArrayList<ArrayList<String>>
* */
public ArrayList<ArrayList<String>> command(String cmd) throws SQLException {
return command(cmd, CommandType.Another);
}
public ArrayList<ArrayList<String>> command(String cmd, CommandType type) throws SQLException {
connectionOpen();
if(connection != null) {
try {
statement = connection.createStatement();
resultSet = statement.executeQuery(cmd);
if(type == CommandType.Select) {
writeDataToList();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
} finally {
try {
resultSet.close();
} catch (Exception e) { /* Ignored */ }
try {
statement.close();
} catch (Exception e) { /* Ignored */ }
try {
connectionClose();
} catch (Exception e) { /* Ignored */ }
}
}else
throw new SQLException("Failed connection");
return info;
}
public enum CommandType{
Select, Another
}
}
I tried to create a sql query using PreparedStatement, but the problem is that you can’t get the connection variable from outside, and I can’t figure out how to correctly form a method that would generate this query.