Posted on February 19th, 2010
5471 views STEP 3 (SQLConnection Class) This simple application is meant to connect to MSSQL server as an EXTRA learning topic in this tutorial. To do this, we will make a new Class. Remember this is Java... everything in Java is a class. For our SQLConnection class I suggest this simple code. You are free to create a better class, but for this tutorial matter, this is just perfect. So we create a new package in the "src" folder and name it "connections" and inside that package we create a new class named�"SQLConnection". And we copy this code: � package connection; import java.sql.*; public class SQLConnection { protected Connection con = null; protected ResultSet rs = null; public SQLConnection(String address, String db, String user, String pass) { try { String conString = "jdbc:sqlserver://"+address+";databaseName="+db; con = DriverManager.getConnection(conString,user,pass); }catch(SQLException sqlError){ //ERROR MANAGEMENT HERE } } public boolean execQuery(String sql) { boolean result = false; try { Statement stmt = con.createStatement(); stmt.execute(sql); result = true; }catch(SQLException sqlError){ //ERROR MANAGEMENT HERE result = false; } return result; } public void execSelectQuery(String sql) { try { Statement stmt = con.createStatement(); this.rs = stmt.executeQuery(sql); }catch(SQLException sqlError){ //ERROR MANAGEMENT HERE } } public void disconnect() { try { con.close(); }catch(SQLException sqlError){ //ERROR MANAGEMENT HERE } } } This simple class will let us connect to the database, perform a select, insert, delete and update statement in the database and finally close the connection.
STEP 4 (Item Class) Now that we have our own database layer we can create a model for our items. This model will let us add items and show the lastest 5 from the database. Heres the simple class I made for this tutorial. You can upgrade it if you like. � package models; import java.sql.SQLException; import connection.SQLConnection; public class Item extends SQLConnection{ public Item() { super("localhost", "todoList", "sqluser", "sqlpass"); } public String[] lastItems(){ String[] result = new String[5]; this.execSelectQuery("SELECT TOP 5 * FROM items ORDER BY id DESC "); int i=0; try { while (this.rs.next()) { result[i] = rs.getString("itemDescription"); i++; } }catch(SQLException sqlError) { //ERROR MANAGEMENT HERE } return result; } public boolean insert(String todo) { String sql = "INSERT INTO items (itemDescription) VALUES ('"+todo+"')"; return this.execQuery(sql); } } This class will be inside the "src" folder, where you'll create a package named "models" and there you'll create this "Item" class.
Now we ended the Second Chapter with this 2 classes. We are almost done. For the last part we'll work on the servlet and finally modify the JSP files a bit.
|