Dhaptar lengkap jinis data JDBC

Saliyane jinis data sing sampeyan ngerti, JDBC ngidini sampeyan nggarap akeh jinis data asli kanggo DBMS. Ing ngisor iki aku bakal dhaptar jinis lan fungsi kanggo entuk:

Jinis Metode
susunan getArray()
AsciiStream getAsciiStream()
BigDecimal getBigDecimal()
BinaryStream getBinaryStream()
gumpalan getBlob()
Boolean getBoolean()
gumpalan getBlob()
Boolean getBoolean()
bita getByte()
bita getBytes()
KarakterStream getCharacterStream()
clob getClob()
Tanggal getDate()
pindho getDouble()
ngambang getFloat()
int getInt()
dawa getLong()
NCCharacterStream getNCharacterStream()
obyek getObject()
Ref getRef()
RowId getRowId()
cendhak getShort()
SQLXML getSQLXML()
String getString()
Wektu getTime()
Stempel wektu getTimestamp()
UnicodeStream getUnicodeStream()
URL getURL()

Kita wis nimbang jinis primitif. Ayo saiki nyoba nggarap obyek.

Tipe data BLOB

Yen sampeyan pengin nyimpen sawetara obyek menyang database, cara paling gampang kanggo nindakake iki yaiku nggunakake jinis SQL BLOB. JDBC duwe mitra sing diarani Blob.

BLOB singkatan saka Binary L arge Object . Iki digunakake kanggo nyimpen macem-macem bait. Jinis Blob ing JDBC minangka antarmuka lan sampeyan bisa nyelehake (lan nampa) data ing rong cara:

  • Nggunakake InputStream
  • Nggunakake array of byte

Tuladha: kolom nomer 3 ngemot jinis BLOB:

Statement statement = connection.createStatement();
    ResultSet results = statement.executeQuery("SELECT * FROM user");
    results.first();

    Blob blob = results.getBlob(3);
    InputStream is = blob.getBinaryStream();

Kanggo nggawe obyek Blob dhewe, sampeyan kudu nggunakake createBlob () fungsi . Tuladha:

String insertQuery = “INSERT INTO images(name, image) VALUES (?, ?);
PreparedStatement statement = connection.prepareStatement(insertQuery);

// Create a Blob object and get an OtputStream from it to write data to it
Blob blob = connection.createBlob();

// Populate the Blob with data...
OutputStream os = blob.setBinaryStream(1);

// Passing Blob as query parameter
statement.setBlob(2, blob);
statement.execute();

Ana rong cara kanggo isi Blob karo data. Sing pertama liwat OutputSteam :

Path avatar = Paths.get("E:\\images\\cat.jpg");
OutputStream os = blob.setBinaryStream(1);
Files.copy(avatar, os);

Lan kaloro - liwat ngisi bait:

Path avatar = Paths.get("E:\\images\\cat.jpg");
byte[] content = Files.readAllBytes(avatar);
blob.setBytes(1, content);

Nyimpen Obyek Jawa menyang Database

Kita wis sinau carane nyimpen obyek binar menyang database: array byte, stream byte, lan liya-liyane. Apa bab obyek Jawa? Kepiye carane nyimpen obyek Jawa menyang database?

Contone, kita duwe kelas Employee Java sing nggambarake karyawan ing sawijining perusahaan:

public class Employee {
    public Integer id;
    public String name;
    public String occupation;
    public Integer salary;
    public Date joinDate;
}

Kepiye carane bisa nyimpen obyek saka kelas iki menyang database nggunakake JDBC?

Nyatane, sampeyan wis ngerti kabeh sing sampeyan kudu ngerti. Pisanan sampeyan kudu nggawe tabel ing database sing cocog karo kelas iki. Contone, iki:

CREATE TABLE employee {
    id INT PRIMARY KEY NOT NULL,
    name VARCHAR(100),
    occupation VARCHAR(100),
    salary INT,
    join_date DATE
}

Lan saiki ayo nulis kode sing bakal nambah obyek saka kelas Karyawan menyang pangkalan:

public static boolean addEmployee(Connection connection, Employee employee) throws Exception {
    	// Create and prepare a query to insert data into the table
    	String insertQuery = "INSERT INTO employee(name, occupation, salary, join_date ) VALUES (?, ?, ?, ?)";
    	PreparedStatement statement = connection.prepareStatement(insertQuery);

    	// Populate the query with data from the Employee object
    	statement.setString(1, employee.name);
    	statement.setString(2, employee.occupation);
    	statement.setInt(3, employee.salary);
    	statement.setDate(4, employee.joinDate);

    	// Execute our query and it returns true if a new row has been added
    	int count = statement.executeUpdate();
    	return count > 0;
    }

Prasaja lan cetha. Cara kasebut bakal apik banget.

Maca obyek Jawa saka database

Kita sinau carane nulis obyek menyang database, saiki ayo nulis kode kanggo maca obyek saka database. Ayo diwiwiti kanthi kode sing maca obyek saka database kanthi ID:

public static Employee getEployeeById(Connection connection, int id) throws Exception {
    	// Create and prepare a query to get an employee from the table
    	PreparedStatement statement = connection.prepareStatement("SELECT * FROM employee WHERE id = ?");
    	statement.setInt(1, id);

    	// Execute our query and it returns null if there are no rows in the query result
    	ResultSet results = statement.executeQuery();
    	if (!results.first())
        	return null;

    	// Populate the Employee object with the data from the ResultSet
    	Employee employee = new Employee();
    	employee.id = results.getInt(1);
    	employee.name = results.getString(2);
    	employee.occupation = results.getString(3);
    	employee.salary = results.getInt(4);
    	employee.joinDate = results.getDate(5);
    	return employee;
}

Lan yen kita ora butuh siji obyek, nanging sawetara? Panjaluk kasebut uga gampang ditulis. Ayo kabeh karyawan perusahaan kita:

public static List<Employee> getAllEployees(Connection connection) throws Exception {
	// Create and execute a query to get employees from the table
	Statement statement = connection.createStatement();
	ResultSet results = statement.executeQuery("SELECT * FROM employee");

	ArrayList<Employee> list = new ArrayList<Employee>();
	while (results.next()) {
        // Populate the Employee object with the data from the current row of the ResultSet
	        Employee employee = new Employee();
	        employee.id = results.getInt(1);
	        employee.name = results.getString(2);
	        employee.occupation = results.getString(3);
	        employee.salary = results.getInt(4);
	        employee.joinDate = results.getDate(5);

	        list.add(employee);
	}
	return list;
}

Miturut cara, yen ana akeh cara kasebut, banjur ing saben wong sampeyan kudu nulis kode sing padha kanggo ngowahi string ResultSet dadi obyek.pegawe. Dadi kode iki bisa dipindhah menyang cara sing kapisah.

Iki bisa migunani banget yen kelas Karyawan ngemot kolom kompleks kaya Enum, InputStream, utawa referensi kanggo obyek liyane sing uga pengin disimpen ing database.