Storing Java Sockets in a mysql database
I have a multithreaded application and I am trying to store the socket variable in a database the database column is a text and it is a mysql database here is my retrieval method:
public Socket getUser1(String game){
Object id =null;
try{
Statement stmt = connection.createStatement();
// Prepare a statement to insert a record
String sql ="SELECT * FROM currentGames where gameid=\"" + game +"\"";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()){
id = rs.getObject(4);
}
}catch (SQLException e){
e.printStackTrace();
}
//System.out.println("Returning id: " + id);
Socket s =null;
s = (Socket)id;
return s;
}
my insert method is as follows:
public String createNewGame(Object socket){
String id ="";
try{
Statement stmt = connection.createStatement();
// Prepare a statement to insert a record
String sql ="INSERT INTO currentGames (user1Socket,currentTurn) values ('" + socket +"','x')";
// Execute the insert statement
stmt.executeUpdate(sql);
sql ="SELECT * FROM currentGames where user1Socket=\"" + socket +"\"";
//System.out.println(sql);
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()){
id = rs.getString(1);
}
sql ="INSERT INTO currentBoards (game) values ('" + id +"')";
// Execute the insert statement
stmt.executeUpdate(sql);
}catch (SQLException e){
e.printStackTrace();
}
//System.out.println("Returning id: " + id);
return id;
}
Everything inserts fine here is an example of the data in the mysql database:
Socket[addr=/192.168.17.109,port=51064,localport=5900]
however when I try to turn that connection back to a socket to create a temporary printwriter to send data to it I always get:
java.lang.ClassCastException: java.lang.String
at game.sqlConnection.getUser1(sqlConnection.java:104)
at game.startServerThread.run(startServer.java:218)
This is how I use the getUser1 example
Socket user1 = sql.getUser1(game);
PrintWriter user1pw =new PrintWriter(user1.getOutputStream(),true);
System.out.println(line);
user1pw.println(line);
I know if I save the item in a vector it works fine but I would really like to save all the sockets in a database rather then a vector because some of my other methods.
I have tried the mysql column types:
blob
text
varchar
All produce the same result that it can't cast from a string. Please help this is driving me CRAZY.
--John

