Database connectivity


We'll now write our DBConnect code, which will make our database table and fill it with information.

Using your lecture notes, write the code to do the following steps:


1) Load up the derby driver.

2) Make a new database called "Results" (run this code, and look in your m:/databases/ directory to see what it creates. If for any reason you ever need to delete the database manually, you just delete the whole Results directory - You will need to do this if you run the database or table creation code more than once). The code to create a database will also give you a connection object that you can use later.

3) Create a standard statement and run the following SQL to create a table: CREATE TABLE Results (Address varchar(255), Burglaries int)

4) Create a scrollable and updatable statement.

5) Run the two following code chunks to test the two ways of inserting data:

	try {
		st2.executeUpdate("INSERT INTO Results VALUES('Home',2)");
		st2.executeUpdate("INSERT INTO Results VALUES('Away',3)");
	} catch (SQLException sqle) {
		sqle.printStackTrace();
	}

and...

	ResultSet rs = null;
	try { 
		rs = st2.executeQuery("SELECT Address,Burglaries FROM Results"); 
		rs.moveToInsertRow();
		rs.updateString("Address", "Pub"); 
		rs.updateInt("Burglaries", 3);
		rs.insertRow(); 
		rs.first();
		rs.close();
	} catch (SQLException sqle) { 
		sqle.printStackTrace(); 
	} 

6) Close the connection.


If you run this (and you've deleted the m:\databases\Results\ directory if necessary), you should see nothing if it works -- it should only come back if there are problems. These will be printed to the eclipse "Console" tab, at the bottom of the application. If there are no errors, the status bar at the top of the console window should just start with <terminated> when it is finished.


This is all very well and good, but it would be nice to check the magic has actually worked. Go on to Part Three where we'll write a class to check this.