JDBC 4: The Code so Far…

The Code so Far

package dbase2016;

/**
 *
 * @author ajb
 */
public class DBase2016 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
    DBase.addStudent();
    DBase.printPupils();
    }

}
package dbase2016;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author ajb
 */
public class DBase {

    private static Connection con;

    DBase() {
    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
    } catch (Exception ex) {
        System.err.println(ex);
    }

    }

    public static void makeConnection() {
    try {
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bluecoat", "root", "");
    } catch (SQLException ex) {
        System.err.println(ex);
    }

    }

    public static void printPupils() {

    Statement statement;
    makeConnection();
    try {
        statement = con.createStatement();
        ResultSet rs = statement.executeQuery("SELECT * FROM Student");

        while (rs.next()) {
        System.out.println("Forename: " + rs.getString("Forename") 
                  + " Surname: " + rs.getString("Surname")
                  + " Gender: " + rs.getString("Gender") 
                  + " Form: " + rs.getString("Form"));
        }

        con.close();

    } catch (SQLException ex) {
        System.err.println(ex);
    }
    }

    public static void addStudent() {

    makeConnection();
    try {
        PreparedStatement prep = con.prepareStatement("INSERT INTO Student (Forename, Surname, Gender, Form) VALUES (?,?,?,?)");
        prep.setString(1, "Last");
        prep.setString(2, "James");
        prep.setString(3, "M");
        prep.setString(4, "9C");

        prep.executeUpdate();

        con.close();

    } catch (SQLException ex) {
        System.err.println(ex);
    }

    }

}

Leave a Reply

Your email address will not be published. Required fields are marked *