i have an function connexion to a database
and i have a code that i have a select and display elements in a combobox
so i want pass on class connexion.java the combobox selectedItem becaue it contains the all of databases that i have
so i want tha classe connexion be dynamic so pass the element selected on this class
i don"t know how can i do that please help me
public class Connexion {
private static Connection conn;
{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(Connexion.class.getName()).log(Level.SEVERE, null, ex);}
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/mohammedia", "root", "123456");
} catch (SQLException ex) {
Logger.getLogger(Connexion.class.getName()).log(Level.SEVERE, null, ex); }
}
public static Connection getconx()
{
return conn;
}
}
Use this class
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.NamingException;
import org.apache.commons.dbcp.BasicDataSource;
import sun.jdbc.rowset.CachedRowSet;
public class SQLConnection {
private static Connection con = null;
private static BasicDataSource dataSource;
//we can enable and disable connection pool here
//true means connection pool enabled,false means disabled
private static boolean useConnectionPool = true;
private static int count=0;
private SQLConnection() {
/*
Properties properties = new Properties();
properties.load(new FileInputStream(""));
maxActive = properties.get("maxActive");
*/
}
public static String url = "jdbc:mysql://localhost:3306/schemaname";
public static String password = "moibesoft";
public static String userName = "root";
public static String driverClass = "com.mysql.jdbc.Driver";
public static int maxActive = 20;
public static int maxIdle = 10;
private static final String DB_URL = "driver.classs.name";
private static final String DB_USERNAME = "database.username";
static {
/*Properties properties = new Properties();
try {
properties.load(new FileInputStream("D:\\CollegeBell\\properties\\DatabaseConnection.properties"));
//properties.load(new FileInputStream("E:\\vali\\CollegeBell\\WebContent\\WEB-INF"));
//properties.load(new FileInputStream("D:\\DatabaseConnection.properties"));
url = properties.getProperty(DB_URL);
System.out.println(url);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
dataSource = new BasicDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setUsername(userName);
dataSource.setPassword(password);
dataSource.setUrl(url);
dataSource.setMaxActive(maxActive);
dataSource.setMinIdle(maxIdle);
dataSource.setMaxIdle(maxIdle);
}
//public static Connection getConnection(String opendFrom) throws SQLException,
public static Connection getConnection(String openedFrom) {
count++;
System.out.println("nos of connection opened till now="+count);
System.out.println("Connection opended from "+openedFrom);
// System.out.println("Connection Opended ");
try {
if (useConnectionPool) {
con = dataSource.getConnection();
System.out.println(dataSource.getMinEvictableIdleTimeMillis());
//dataSource.setMaxWait(15000);
System.out.println(dataSource.getMaxWait());
System.out.println(count );
} else {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, userName, password);
}
}
//System.out.println("Connection : " + con.toString());
catch (SQLException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
return con;
}
public static void closeConnection(Connection con, String closedFrom)
{
//System.out.println("Connection closed from: " + con.toString());
// System.out.println("Connection closed from: " + closedFrom);
//log.info("Connection closed from: " + closedFrom);
if(con != null){
count--;
System.out.println("Connection count value after closing="+count);
System.out.println("Connection closed from: " + closedFrom);
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//added by nehal
public static void closeStatement(Statement ps, String closedFrom)
{
if(ps != null){
System.out.println("Statement closed from: " + closedFrom);
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void closePreparedStatement(PreparedStatement ps, String closedFrom)
{
if(ps != null){
System.out.println("Statement closed from: " + closedFrom);
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void closeResultSet(ResultSet rs, String closedFrom)
{
if(rs != null){
System.out.println("ResultSet closed from: " + closedFrom);
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//added by nehal
/*public static ResultSet executeQuery(String query) throws Exception {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
CachedRowSet crset = null;
try {
con = getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(query);
crset = new CachedRowSet();
crset.populate(rs);
} catch (Exception e) {
throw e;
} finally {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (con != null && !con.isClosed()) {
con.close();
}
}
return crset;
}
public static int executeUpdate(String query) throws Exception {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
int rows = -1;
try {
con = getConnection();
stmt = con.createStatement();
rows = stmt.executeUpdate(query);
} catch (Exception e) {
throw e;
} finally {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (con != null && !con.isClosed()) {
con.close();
}
}
return rows;
}
public static boolean execute(String query) throws Exception {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
boolean rowsreturned = false;
try {
con = getConnection();
stmt = con.createStatement();
rowsreturned = stmt.execute(query);
} catch (Exception e) {
throw e;
} finally {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (con != null && !con.isClosed()) {
con.close();
}
}
return rowsreturned;
}*/
/*
* public static void closeConnection(Connection con) { try { con.close();
* con=null; } catch (SQLException e) { // TODO Auto-generated catch block
* e.printStackTrace(); } }
*/
}
A JComboBox accepts any kind of object, so you can simply do something like this.
Connection con = new Connection();
JComboBox box = getBox();
box.addItem(con);
And to retreive the value:
JComboBox box = getBox();
Connection con = (Connection)box.getSelectedItem();
However in your Connection class you must override the toString() function, because this is used to display the box.
class Connection
{
public String toString()
{
return "BoxItemDisplayvalue"; <--- here you must put something meaningfull which is displayed in the box.
}
}
So you can instantiate a connection representing the connection that you want, and when the user selects an item from the combobox, you will have the connection it represents.
For what i understand, you have 2 classes..
One the gui where you have a comboBox with the schema name where u want to get connected.
So you have to have a EventListener to "listen" when the submit button is pressed.
For example:
Connection con = null;
JButton submitButton = new JButton("Confirm db");
submitButton.addActionListener(new MyConnectionListener());
..
//Could be inner class
class MyConnectionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent evt){
if(cmb.getSelectedItem() != null){
con = Connection.getConx(cmb.getSelectedItem().toString());
}
}
}
And in your Connexion class
public class Connexion {
public static Connection getconx(String schema)
{
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(Connexion.class.getName()).log(Level.SEVERE, null, ex);}
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/"+schema, "root", "123456");
} catch (SQLException ex) {
Logger.getLogger(Connexion.class.getName()).log(Level.SEVERE, null, ex); }
}
return conn;
}
}
Related
I am having a problem with my mysql setBanned statement. I am trying to set a user banned into the database, but it is throwing me a "No operation is allowed after connection closed." can anyone help me?
It throws an error on the
statement.setString(3, reason);
In the setBanned code.
Current setBanned code:
public boolean setBanned(Player player, boolean state, String reason){
Connection conn = null;
PreparedStatement statement = null;
String setBanned = "INSERT INTO `test_bans` (UUID, BANNED, REASON) VALUES ( ?, ?, ?)";
String setUnbanned = "UPDATE `test_bans` SET BANNED= ? WHERE UUID= ?";
try{
conn = MySql.getConnection();
if(isBanned(player) && state == false){
statement = conn.prepareStatement(setUnbanned);
statement.setBoolean(1, state);
statement.setString(2, player.getUniqueId().toString());
statement.executeUpdate();
} else {
statement = conn.prepareStatement(setBanned);
statement.setString(1, player.getUniqueId().toString());
statement.setBoolean(2, state);
statement.setString(3, reason);
statement.executeUpdate();
}
} catch (SQLException e){
e.printStackTrace();
} finally {
if(statement != null){
try{
statement.close();
} catch (SQLException e){
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e){
e.printStackTrace();
}
}
}
return false;
}
isBanned code:
public boolean isBanned(Player player){
Connection conn = null;
PreparedStatement statement = null;
ResultSet result = null;
String query = "SELECT BANNED FROM `test_bans` WHERE UUID= ?";
try{
conn = MySql.getConnection();
statement = conn.prepareStatement(query);
statement.setString(1, player.getUniqueId().toString());
result = statement.executeQuery();
return result.next();
} catch (SQLException e){
e.printStackTrace();
} finally {
if (result != null){
try{
result.close();
} catch (SQLException e){
e.printStackTrace();
}
}
if(statement != null){
try{
statement.close();
} catch (SQLException e){
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e){
e.printStackTrace();
}
}
}
return false;
}
EDIT: MySQL Class
public class MySql {
private static String DATABASE_NAME ="testing_database";
private static String DATABASE_IP ="localhost:3306";
private static String connection ="jdbc:mysql://"+DATABASE_IP+"/"+DATABASE_NAME;
private static String username ="root";
private static String password ="pass";
private static Connection conn;
public static void handleConnection(){
Bukkit.getServer().getLogger().info("Establishing connection to MySQL Database....");
try{
conn = DriverManager.getConnection(connection, username, password);
if(!conn.isClosed()){
Bukkit.getServer().getLogger().info("Successfully synced with MySQL!");
return;
}
return;
}
catch (SQLException e){
e.printStackTrace();
return;
}
}
public static void disconnectConnection(){
Bukkit.getServer().getLogger().info("Disconnecting from MySQL Databse....");
try{
conn.close();
if(conn.isClosed()){
Bukkit.getServer().getLogger().info("Successfully Disconnected");
}
return;
}
catch(SQLException e){
e.printStackTrace();
return;
}
}
public static boolean setupTables(){
try{
System.out.println("Checking Tables");
conn.prepareStatement("CREATE TABLE IF NOT EXISTS test_ranks (UUID VARCHAR(255), RANK VARCHAR(25));").executeUpdate();
conn.prepareStatement("CREATE TABLE IF NOT EXISTS test_bans (UUID VARCHAR(255), BANNED BOOLEAN, REASON TEXT);").executeUpdate();
return true;
}
catch(SQLException e){
e.printStackTrace();
return false;
}
}
public static boolean checkConnection(){
try{
if((conn != null) && (!conn.isClosed())){
return true;
}
return false;
}
catch(SQLException e){
e.printStackTrace();
return false;
}
}
public static Connection getConnection(){
try {
if(conn.isClosed()){
connectMySQL();
return conn;
}
if(conn == null){
connectMySQL();
return conn;
}
} catch (SQLException e){
e.printStackTrace();
}
return conn;
}
public static void connectMySQL(){
try {
conn = DriverManager.getConnection(connection, username, password);
return;
} catch(SQLException e){
e.printStackTrace();
}
}
}
Your question is not clear....
There isn't any class MySql.If its custom class ...provide its code snippet.
Actual way of using Mysql JDBC connections
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection("jdbc:mysql://hostname:port/dbname","username", "password");
//Create statement
//Execute statement
//Iterate over results
//close statement
conn.close(); // close connection
in this line if(isBanned(player) && state == false){ you are calling the isBanned() and after that method executes the connection is closed in the line
conn.close();
in the isBannedMethod()
therefore when it comes to the else portion the connection is already closed.
You need to get another connection
Add
else {
**conn = MySql.getConnection();**
statement = conn.prepareStatement(setBanned);
private static String dbURL = "jdbc:mysql://localhost:3306/mydb";
private static String username = "secret";
private static String password = "secret";
private static Connection conn = null;
public static void initDbConnection(){
try {
conn = DriverManager.getConnection(dbURL, username, password);
Class.forName("com.mysql.jdbc.Driver");
} catch (SQLException e1) {
e1.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void test3(){
initDbConnection();
try{
String sql = "SELECT * FROM Products";
Statement statement = conn.createStatement();
ResultSet result = statement.executeQuery(sql);
while (result.next()){
String name = result.getString("name");
System.out.println(name);
}
}
catch (SQLException ex) {
ex.printStackTrace();
}
}
Why I'm getting null pointer exception on conn even though I called the initDbConnection() on test3() ? How will I elimate this problem?
Class.forName("com.mysql.jdbc.Driver");
should be the first line. As this load the mysql driver in the memory. Then you will acquire the connection.
So it should be
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(dbURL, username, password);
} catch (SQLException e1) {
e1.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
It seems a very basic question but I couldn't find any resolution for it.
I have following code with me:
package com.test.db.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCConnect
{
private Connection conn = null;
private final String uname = "root";
private final String passwd = "test#123";
private String url = "jdbc:mysql://127.0.0.1:3306/TrainDB";
private final String className = "com.mysql.jdbc.Driver";
public void initConnection()
{
try
{
if(this.conn == null || this.conn.isClosed())
{
try
{
Class.forName (className).newInstance ();
this.conn = DriverManager.getConnection(url, uname, passwd);
System.out.println("database connection established.");
}
catch(SQLException sqe)
{
sqe.printStackTrace();
}
catch (InstantiationException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
catch(SQLException sqle)
{
sqle.printStackTrace();
}
//return this.conn;
}
public void disconnect()
{
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
public void insertData(String sql)
{
PreparedStatement s;
try
{
if(conn == null || conn.isClosed())
{
initConnection();
}
s = conn.prepareStatement(sql);
int count = s.executeUpdate ();
s.close ();
System.out.println (count + " rows were inserted");
}
catch (SQLException e)
{
e.printStackTrace();
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception se) { /* ignore close errors */ }
}
}
}
public ResultSet query(String sql)
{
Statement s = null;
try
{
if(this.conn == null || this.conn.isClosed())
{
initConnection();
}
s = conn.createStatement();
s.executeQuery(sql);
ResultSet rs = s.getResultSet();
System.out.println("lets see " + rs.getFetchSize());
return rs;
}
catch(SQLException sq)
{
System.out.println("Error in query");
return null;
}
finally
{
try {
s.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I am using JDBCConnect in a different class:
import java.sql.ResultSet;
import java.sql.SQLException;
public class traininfo
{
public static void main(String[] args)
{
JDBCConnect jdbcConn = new JDBCConnect();
String sql = "SELECT id FROM testtable";
ResultSet rs = jdbcConn.query(sql);
try {
System.out.println(rs.getFetchSize());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(rs != null)
{
try
{
while(rs.next())
{
System.out.println(rs.getString("id"));
}
rs.close();
}
catch(SQLException sqe)
{
}
}
jdbcConn.disconnect();
}
}
I am not using concurrent calls for insertion and reads. If I use the same query in mysql-workbench (client), I am getting proper results but using the mentioned code, I am getting
database connection established.
lets see 0
0
Database connection terminated
Please suggest me what I am missing?
Most probably it's because you're closing Statement before you are using it's ResultSet. It's strange that it doesn't throw an exception, but this is not correct anyway.
As per Statement.close method JavaDoc:
When a Statement object is closed, its current ResultSet object, if one exists, is also closed.
I suggest to use some kind of callback to retrieve results from ResultSet before it's closed e.g.:
public <T> T query(String sql, IResultSetHandler<T> resultSetHandler ) throws SQLException {
Statement statement = null;
try {
statement = connection.createStatement();
final ResultSet rs = connection.executeQuery(sql);
final T result = resultSetHandler.handle(rs);
return result;
} finally {
if(statement != null) {
statement.close();
}
}
}
public interface IResultSetHandler<T> {
T handle(ResultSet rs);
}
public static void main(String[] args) {
JDBCConnect jdbcConn = new JDBCConnect();
List<String> ids = jdbcConn.query(sql, new IResultSetHandler<List<String>>() {
public List<String> handle(ResultSet rs) {
List<String> ids = new ArrayList<String>();
while(rs.next()) {
ids.add(rs.getString("id"));
}
return ids;
}
});
}
Or to use commons apache dbutils library which does exactly the same.
ResultSet.getFetchSize() lets you know the maximum number of rows that the connection will fetch at once. You can set it with ResultSet.setFetchSize(int). See also the official documentation. It does not tell you how many rows in total you will get. If the fetch size is left to zero, JDBC decides on its own.
Other than that, refer to Yura's answer which addresses the core of your problem.
Could it be because you never call InsertRows, as it never shows that 'X rows were inserted'
i'm trying to establish connection with mysql database through file properties and then run the information from servlet. my Connection class looks like this:
public class pageDao {
private Connection connection;
private Statement statement;
private pageDao() {
Properties prop = new Properties();
try {
//Class.forName("oracle.jdbc.driver.OracleDriver");
//Class.forName("org.gjt.mm.mysql.Driver");
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException cnfe) {
System.out.println("Error loading driver: " +cnfe);
}
try {
try {
//load a properties file
prop.load(new FileInputStream("config.properties"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String db = prop.getProperty("database");
String dbuser = prop.getProperty("dbuser");
String dbpassword = prop.getProperty("dbpassword");
connection = DriverManager.getConnection(db,dbuser,dbpassword);
} catch (SQLException e) {
e.printStackTrace();
}
}
private static pageDao thisDao;
public static pageDao gedDao()
{
if(thisDao == null)
thisDao = new pageDao();
return thisDao;
}
public PageData getPage(String id)
{
PageData data = new PageData();
try {
statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from pages where id='"+id+"'");
if(rs.next())
{
data.setId(rs.getString("id"));
data.setParentid(rs.getString("parentid"));
data.setTitle(rs.getString("title"));
data.setTitle4menu(rs.getString("title4menu"));
data.setKeywords(rs.getString("keywords"));
data.setDescription(rs.getString("description"));
data.setMaintext(rs.getString("maintext"));
}
else
return null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return data;
}
when i run it, it doesn't show the mistake that connection wasn't established, but when it gets to the
public PageData getPage(String id) {
PageData data = new PageData();
try {
statement = connection.createStatement();
it throws java.lang.NullPointerException.
can anybody help me out with that?
there is no issue with code.
check your passing parameter ...
check sample
private Connection getConnection() {
try {
String dbUrl = "jdbc:mysql://localhost:3306/projectmining";
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(dbUrl, "root", "admin");
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
I use this code to get a Blob from a MySql database and it works fine, when i use it for an sqlite database it throws a StreamCorruptedException
public static SessionData getIvissSession(BigInteger id) throws IvissDatabaseException {
SessionData sd = null;
PreparedStatement pstmt = null;
Connection con = null;
try {
con = getConnection();
pstmt = con.prepareStatement("SELECT ivissblob FROM iviss_session_table WHERE id =?");
pstmt.setLong(1, Long.parseLong(id.toString()));
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
byte[] ivissblob = rs.getBytes("ivissblob");
ObjectInputStream objectIn = new ObjectInputStream(new ByteArrayInputStream(ivissblob));
sd = (SessionData) objectIn.readObject();
objectIn.close();
}
} catch (SQLException e) {
throw new IvissDatabaseException(Constants.ERROR_202);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (pstmt != null) {
pstmt.close();
}
if (con != null) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return sd;
When I use the SqLite Database:
java.io.StreamCorruptedException: invalid stream header: 61742E75
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:797)
at java.io.ObjectInputStream.(ObjectInputStream.java:294)
Why is there a differnt behaviour?
Here how I write into the database:
public static void insertIntoTable(BigInteger id, SessionData sd, byte[] rtsd, IvissWorker ivissWorker) {
PreparedStatement pstmt = null;
Connection con = null;
try {
con = getConnection();
pstmt = con
.prepareStatement("REPLACE INTO iviss_session_table (id, ivissblob, rtblob, lastaccess) VALUES(?,?,?,?)");
pstmt.setLong(1, Long.parseLong(id.toString()));
pstmt.setObject(2, sd);
pstmt.setObject(3, rtsd);
pstmt.setDate(4, new Date(System.currentTimeMillis()));
pstmt.executeUpdate();
} catch (SQLException e) {
ivissWorker.getIvissWorkerOutputHandler().addError(Constants.ERROR_205, "", DbConfiguration.getDbUri());
} finally {
try {
if (pstmt != null) {
pstmt.close();
}
if (con != null) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Additional information sqlite driver version:
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.7.2</version>
a solution of the problem given from a colleague:
Insert the object not with method .setObject, but with .setBytes instead.
public static void insertIntoTable(BigInteger id, SessionData sd, byte[] rtsd, IvissWorker ivissWorker) {
PreparedStatement pstmt = null;
Connection con = null;
try {
con = getConnection();
pstmt = con
.prepareStatement("REPLACE INTO iviss_session_table (id, ivissblob, rtblob, lastaccess) VALUES(?,?,?,?)");
pstmt.setLong(1, Long.parseLong(id.toString()));
pstmt.setBytes(2, IvissUtil.getBytes(sd));
pstmt.setObject(3, rtsd);
pstmt.setDate(4, new Date(System.currentTimeMillis()));
pstmt.executeUpdate();
// System.out.println("Stored/Replaced session with ID: " + id +
// " in table.");
} catch (SQLException e) {
ivissWorker.getIvissWorkerOutputHandler().addError(Constants.ERROR_205, "", DbConfiguration.getDbUri());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (pstmt != null) {
pstmt.close();
}
if (con != null) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
and the getBytes method:
public static byte[] getBytes(Object obj) throws java.io.IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
oos.close();
bos.close();
byte[] data = bos.toByteArray();
return data;
}
Now it works with sqlite and MySql