Buat database Mysql, kemudian buat pada netbeans seperti gambar dibawah ini :
a. Person.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dbapp;
/**
*
* @author isca
*/
public class Persons {
private int id;
private String nama;
private String alamat;
private String telp;
public Persons() {
}
public String getAlamat() {
return alamat;
}
public void setAlamat(String alamat) {
this.alamat = alamat;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNama() {
return nama;
}
public void setNama(String nama) {
this.nama = nama;
}
public String getTelp() {
return telp;
}
public void setTelp(String telp) {
this.telp = telp;
}
}
b. PersonManager.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dbapp;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author isca
*/
public class PersonsManager {
Connection con = null;
Statement st = null;
String url = "jdbc:mysql://localhost:3306/dbapp_11080978";
String user = "root";
String pwd = "password";
public PersonsManager() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(url, user, pwd);
st = con.createStatement();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public List getPersons() {
ResultSet rs = null;
List persons = new ArrayList();
try {
rs = st.executeQuery("SELECT id,nama,alamat,telp FROM tperson");
while (rs.next()) {
Persons p = new Persons();
p.setId(rs.getInt(1));
p.setNama(rs.getString(2));
p.setAlamat(rs.getString(3));
p.setTelp(rs.getString(4));
persons.add(p);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return persons;
}
public int insert(Persons p) {
int result=0;
try {
result = st.executeUpdate("INSERT INTO tperson(id,nama,alamat,telp)"
+ "VALUES(" + p.getId() + ",'" + p.getNama() + "','" + p.getAlamat() + "'," +
"'"+ p.getTelp() + "')");
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
public int delete(Persons p) {
int result=0;
try {
result=st.executeUpdate("DELETE FROM tperson WHERE ID="+p.getId()+"");
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
}
0 komentar:
Posting Komentar