package com.devdaily.sqlprocessortests; import java.sql.*; import com.missiondata.oss.sqlprocessor.SQLProcessor; /** * This class shows how to properly set the values of variables using "set" * methods, which are an improvement over the "?" approach of * PreparedStatements. */ public class SQLProcessorDemo2 { Connection conn; public static void main(String[] args) { new SQLProcessorDemo2(); } public SQLProcessorDemo2() { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); String url = "jdbc:mysql://localhost/coffeebreak"; conn = DriverManager.getConnection(url,"root", "ibmis4me"); doTests(); conn.close(); } catch (ClassNotFoundException ex) {System.err.println(ex.getMessage());} catch (IllegalAccessException ex) {System.err.println(ex.getMessage());} catch (InstantiationException ex) {System.err.println(ex.getMessage());} catch (SQLException ex) {System.err.println(ex.getMessage());} } private void doTests() { doSelectTest(); doInsertTest(); doSelectTest(); doUpdateTest(); doSelectTest(); doDeleteTest(); doSelectTest(); } /** Same as SQLProcessorDemo1 */ private void doSelectTest() { System.out.println("[OUTPUT FROM SELECT]"); String query = "SELECT COF_NAME, PRICE FROM COFFEES"; SQLProcessor sqlProcessor = new SQLProcessor("The Coffee Break SELECT Test", query) { protected void process(ResultSet rs) throws SQLException { String s = rs.getString("COF_NAME"); float n = rs.getFloat("PRICE"); System.out.println(s + " " + n); } }; sqlProcessor.execute(conn); } /** * This is our first use of the SQLProcessor "set" methods. * This is much better than using JDBC statements, as the underlying * PreparedStatements keep you from having to worry about SQL Injection hacks. * And the syntax is much more obvious, and less prone to errors, than * the JDBC PreparedStatement syntax. */ private void doInsertTest() { System.out.print("\n[Performing INSERT] ... "); SQLProcessor sqlProcessor = new SQLProcessor("The Coffee Break INSERT Test", "INSERT INTO COFFEES VALUES (|coffeeName|,|supplierID|,|price|,|sales|,|total|)"); sqlProcessor.set("coffeeName","BREAKFAST BLEND"); sqlProcessor.set("supplierID",200); sqlProcessor.set("price",7.99); sqlProcessor.set("sales",0); sqlProcessor.set("total",0); sqlProcessor.execute(conn); } private void doUpdateTest() { System.out.print("\n[Performing UPDATE] ... "); SQLProcessor sqlProcessor = new SQLProcessor("The Coffee Break UPDATE Test", "UPDATE COFFEES SET PRICE=|price| WHERE COF_NAME=|coffeeName|"); sqlProcessor.set("price", 4.99); sqlProcessor.set("coffeeName", "BREAKFAST BLEND"); sqlProcessor.execute(conn); } private void doDeleteTest() { System.out.print("\n[Performing DELETE] ... "); SQLProcessor sqlProcessor = new SQLProcessor("The Coffee Break DELETE Test", "DELETE FROM COFFEES WHERE COF_NAME=|coffeeName|"); sqlProcessor.set("coffeeName", "BREAKFAST BLEND"); sqlProcessor.execute(conn); } }