Membuat Koneksi 2

1.             Membuat class java untuk koneksi 2 dengan nama Creat.java 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Create {
        public static void main(String[] args) throws SQLException {
        String insert = "Insert into mahasiswa values(?,?,?,?,?,?)";
        Connection connection = null;
        PreparedStatement ps = null;
        try {
            connection = Koneksi.getKoneksi();
            ps = connection.prepareStatement(insert);
            ps.setString(1, null); //id
            ps.setString(2, "Uzumaki Naruto"); //nama
            ps.setString(3, "110011009"); //nim
            ps.setString(4, "L"); //jeniskelamin
            ps.setString(5, "0815738838"); //telepon
            ps.setString(6, "email@mail.com"); //email
            ps.executeUpdate();
            System.out.println("Insert Berhasil");
        } catch (SQLException e) {
            System.out.println("Error : " + e.getMessage());
        }finally{
           if(ps!=null){
               ps.close();
           }
        }
    }

Script Creat.java
2.             Membuat class java baru dengan nama Read.
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Read {
    public static void main(String[] args) throws SQLException {
        String read = "select * from mahasiswa";
        Connection connection = null;
        Statement statement = null;
        ResultSet rs = null;

        try {
            connection = Koneksi.getKoneksi();
            statement = connection.createStatement();
            rs = statement.executeQuery(read);
            while (rs.next()) {
                System.out.println("ID\t\t : " + rs.getString("id"));
                System.out.println("Nama\t\t : " + rs.getString("nama"));
                System.out.println("NIM\t\t : " + rs.getString("nim"));
                System.out.println("Jenis Kelamin\t : " + rs.getString("jeniskelamin"));
                System.out.println("Telepon\t\t : " + rs.getString("telepon"));
                System.out.println("Email\t\t : " + rs.getString("email"));
            }
        } catch (SQLException e) {
            System.out.println("Error  : " + e.getMessage());
        }finally{
            if(statement!=null){
                statement.close();
            }
        }
    }
}



Script Read.java
3.             Setelah itu di run file dengan car aklik kanan pada read..java lalau memilih run file maka akan menghasilkan output seperti berikut :


Output Read.java

No comments:

Post a Comment