hi everyone i had been working on a project using random files (.dat) and now i want to change it to use a database instead. the thing is my project is quite long and it would be a hassle to go and change code.

i had used hash tables to store data and i just flused it into my randomfile. here is my code to read and write data. any suggestions on changing it to database.

thanks in advance

static void writeFiles(){
    try{
      FileOutputStream outStream;
      ObjectOutputStream ooStream;

      outStream = new FileOutputStream("CustomerList.dat");
      ooStream = new ObjectOutputStream(outStream);
      
      ooStream.writeObject(CusList);
      ooStream.flush();
      outStream.close();
      
      
      outStream = new FileOutputStream("ProductList.dat");
      ooStream = new ObjectOutputStream(outStream);
      
      ooStream.writeObject(ProdList);
      ooStream.flush();
      outStream.close();
      
      outStream = new FileOutputStream("SalesmanList.dat");
      ooStream = new ObjectOutputStream(outStream);
      
      ooStream.writeObject(sleList);
      ooStream.flush();
      outStream.close();
      
      outStream = new FileOutputStream("Transaction_Products.dat");
      ooStream = new ObjectOutputStream(outStream);
      
      ooStream.writeObject(tpList);
      ooStream.flush();
      outStream.close();
      
      outStream = new FileOutputStream("Temp.dat");
      ooStream = new ObjectOutputStream(outStream);
      
      ooStream.writeObject(tempList);
      ooStream.flush();
      outStream.close();
      
      System.out.println("files saved");
      
    }
    catch (IOException exc){System.out.println("Error writing file!");}
  }
  static void readFiles(){
    try{
      FileInputStream inStream;
      ObjectInputStream oiStream;
      
      try{
    	inStream = new FileInputStream("ProductList.dat");
    	oiStream = new ObjectInputStream(inStream);
    	ProdList = (ProductList)oiStream.readObject();
      }
      catch(FileNotFoundException exc){
        System.out.println("prodlist not found.");

      }
      
      try{
      	inStream = new FileInputStream("SalesmanList.dat");
      	oiStream = new ObjectInputStream(inStream);
      	sleList = (SalesmanList)oiStream.readObject();
        }
        catch(FileNotFoundException exc){
          System.out.println("salelist not found.");

        }
        
        try{
          	inStream = new FileInputStream("Transaction_Products.dat");
          	oiStream = new ObjectInputStream(inStream);
          	tpList = (TPList)oiStream.readObject();
            }
            catch(FileNotFoundException exc){
              System.out.println("tplist not found.");

            }
      
      inStream = new FileInputStream("CustomerList.dat");
      oiStream = new ObjectInputStream(inStream);
      
      CusList = (CustomerList)oiStream.readObject();
      
  
      
      System.out.println("files reloaded.");
    }
    catch (FileNotFoundException exc){
      System.out.println("File/s not found!");
      writeMisc();
    }
    catch(IOException exc){
      System.out.println("Error reading file! Creating new database.");

      writeMisc();
    }
    catch(ClassNotFoundException exc){
      System.out.println("Class not found.");
    }
  }
  //read/write miscellaneous files
  static void writeMisc(){
    String settings = Premier_Customer.getCount()+" ";
    String settings2 = Prod.getCount()+" ";
    String settings3 = Salesman.getCount()+" ";
   
    try{
      FileWriter outStream = new FileWriter("misc.inf");
      outStream.write(settings+"\n");
      outStream.write(settings2+"\n");
      outStream.write(settings3);
      outStream.close();
      System.out.println("miscellaneous files saved.");
    }
    catch(IOException exc){System.out.println("error writing misc file.");}
  }
  static void readMisc(){
    try{
      BufferedReader inStream = new BufferedReader(new FileReader("misc.inf"));
      
      int setThis = Integer.parseInt(inStream.readLine().trim());
      Premier_Customer.setInitialCount(setThis);
      Prod.setInitialCount(setThis);
      Salesman.setInitialCount(setThis);
      

      System.out.println("miscellaneous files reloaded.");
    }
    catch(IOException exc){
      System.out.println("Error reading misc file");
      writeMisc();
    }
  }

1) define table structure
2) learn about jdbc
3) create a decent architecture for your persistence layer
4) decouple the persistence code out of your existing application
5) replace the calls to the decoupled persistence code with calls to the new persistence layer

i know about jdbc. i could add simple stuff.its using hashtables in jdbc which im not familiar with. any help would or sample code would be appreciated.

use the keys from the hashtable as keys in your database, the values as datafields.
Effectively a hashtable can be mapped directly to a database table like that.
You will have to somehow ensure you get unique primary keys if you want a primary key on the database table, but that is usually handled with some sort of autoincrement field.

ok so can u give me an idea as to how my sql statement would be??? lets say my hashtable contains

Prod temp = new Prod(pd,pc,up,qty);
            ProdList.put(temp.getIdNumber(),temp);

where prod has declaration

public Prod(String D, int C, int P, int Q){
	  Description = D;
	  Cost = C;
	  Price = P;
	  Quan = Q;
	  
    setCount();
  }

set count sets a new id number smthng like auto increment.

now can u give me how to code that.and then how would i load it back to the hash table.

is it going to be something like

Product selectedProd;

selectedProd = (Product )ProdList.get(id);

 String query = "INSERT INTO Product VALUES( " + id + ", " + selectedProd.getDescription()+ ", " + selectedProd.getCost()+ ", " + selectedProd.getPrice()+ ", " + selectedProd.getQuan()+ ");";
        stmt.execute(query)

but this way i will need to provide it with an id.is there a way i could just put all the data in hashtable into the database??

What I know there is no super easy way to write your hashtable to a database, since you want to store a java object. The most common tool/framework to do stuff like this is hibernate which lets you define java objects to database mapping and then you can simply retrieve and store object in the database without having to handle sql to much.

You basically make a hibernate mapping file, an xml file which stores information on how an object is stored in the database and its relations to other objects etc. Then you have the corresponding java Object Prod. You can then use hibernate like the following...

Get a session
start a database transaction
//do work
commit transaction

where work can be for example.

Query q = session.createQuery("from Prod");
List<Prod> prods = q.list();

or create a new Prod and persist it...

Prod p = new Prod( input... );
session.save(p);

This way you don't have to handle sql inserts and getting out info from a db table and storing it to an object, hibernate does that for you.

If you use netbeans for example for your project there are built in tools that helps you create everything you need for hibernate to work. There are wizards that can access your DB, create suitable mapping and java Object files, and then you just use it. But you'll need to read a little on the basics of hibernate.

Hope I didn't complicate things to much, it is actually pretty ease to use once you get a feel for the framework.

Wrong, it's "super easy" for anyone who knows a tiny bit about Java.
No Hibernate or other persistence framework needed, just common sense.

In fact it's so trivial the only way to be more specific than I already was would be to give him all the code to actually do it, and I'm not going to do that.

i dont need the whole code. just need an example.i dont do java.my feild is c++.if it wasnt my requirement to do itin java.i wouldnt have so much hassle.

You can access a Hashtable using an Iterator, retrieving Entry objects containing key/value pairs.
For each of those, retrieve the key and value and insert it into the database using standard jdbc functionality.

You'll need to learn some Java to be able to do that, can't be helped. So you will need to "do Java".

ahh i 4got abt iterator. k i try it n feed u back.although if u could than help me out with some code. like give an example or something.the thing which im considered about is.once ive accessed the hashtable it becomes empty. so i need to read and write to my files to be able to feed back to the hashtable.how do i attain that.

Wrong, it's "super easy" for anyone who knows a tiny bit about Java.
No Hibernate or other persistence framework needed, just common sense.

In fact it's so trivial the only way to be more specific than I already was would be to give him all the code to actually do it, and I'm not going to do that.

Yours and mine definition of what is trivial and super easy could be discussed, obviously not trivial or super easy to some. And I don't see why using JDBC would be much simpler than hibernate. With hibernate you will not have to handle how objects are persisted, retrieved etc. With JDBC you will.

Anyways the solution to this isn't a couple of lines of code (maybe just a bit more) if thats what your after. If you want to use JDBC java has a great getting started guide (link follows) with very good examples which should get you going pretty fast if you are familiar enough with java.

JDBC
http://java.sun.com/javase/6/docs/technotes/guides/jdbc/getstart/GettingStartedTOC.fm.html

Hibernate
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/tutorial.html

Most of chapter 1 in the hibernate tutorial can be done with wizards included in IDEs like netbeans, but it's good if you get a grasp of how config files and mapping files works, and the basics of how hibernate operates, sessions, transactions, hibernate query language (similar to sql but works with java objects instead of tables and columns) etc.

Which ever method you choose you will most definitely end up changing some parts of you code and decouple stuff, that cant be avoided if you don't like the famous architecture of spaghetti-code.

thanks everyone for the help i naged to convert it totally without hibernating.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.