Lista completă a tipurilor de date JDBC
Pe lângă tipurile de date pe care le cunoașteți, JDBC vă permite să lucrați cu multe tipuri de date native pentru DBMS. Mai jos voi enumera tipurile și funcțiile pentru a le obține:
Tip | Metodă |
---|---|
matrice | getArray() |
AsciiStream | getAsciiStream() |
BigDecimal | getBigDecimal() |
BinaryStream | getBinaryStream() |
blob | getBlob() |
boolean | getBoolean() |
blob | getBlob() |
boolean | getBoolean() |
octeți | getByte() |
octeți | getBytes() |
CharacterStream | getCharacterStream() |
Clob | getClob() |
Data | getDate() |
Dubla | getDouble() |
pluti | getFloat() |
int | getInt() |
Lung | getLong() |
NCharacterStream | getNCharacterStream() |
Obiect | getObject() |
Ref | getRef() |
RowId | getRowId() |
Mic de statura | getShort() |
SQLXML | getSQLXML() |
Şir | getString() |
Timp | Fă-ți timp() |
Timestamp-ul | getTimestamp() |
UnicodeStream | getUnicodeStream() |
URL | getURL() |
Am luat în considerare deja tipurile primitive. Să încercăm acum să lucrăm cu obiecte.
Tipul de date BLOB
Dacă doriți să salvați un obiect în baza de date, atunci cea mai ușoară modalitate de a face acest lucru este utilizarea tipului SQL BLOB. JDBC are omologul său numit Blob.
BLOB înseamnă Binary L arge Object . _ Este folosit pentru a stoca o serie de octeți. Tipul Blob din JDBC este o interfață și puteți pune (și primi) date în ea în două moduri:
- Folosind InputStream
- Folosind o matrice de octeți
Exemplu: coloana numărul 3 conține tipul BLOB:
Statement statement = connection.createStatement();
ResultSet results = statement.executeQuery("SELECT * FROM user");
results.first();
Blob blob = results.getBlob(3);
InputStream is = blob.getBinaryStream();
Pentru a vă crea propriul obiect Blob, trebuie să utilizați funcția createBlob() . Exemplu:
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();
Există două moduri de a popula un blob cu date. Prima este prin OutputSteam :
Path avatar = Paths.get("E:\\images\\cat.jpg");
OutputStream os = blob.setBinaryStream(1);
Files.copy(avatar, os);
Și al doilea - prin umplerea cu octeți:
Path avatar = Paths.get("E:\\images\\cat.jpg");
byte[] content = Files.readAllBytes(avatar);
blob.setBytes(1, content);
Salvarea unui obiect Java într-o bază de date
Am învățat cum să salvăm obiecte binare în baza de date: matrice de octeți, fluxuri de octeți și așa mai departe. Dar obiectele Java? Cum salvăm un obiect Java într-o bază de date?
Să presupunem că avem o clasă Employee Java care descrie un angajat al unei companii:
public class Employee {
public Integer id;
public String name;
public String occupation;
public Integer salary;
public Date joinDate;
}
Cum putem salva un obiect din această clasă în baza de date folosind JDBC?
De fapt, știi deja tot ce trebuie să știi. Mai întâi trebuie să creați un tabel în baza de date care corespunde acestei clase. De exemplu, acesta:
CREATE TABLE employee {
id INT PRIMARY KEY NOT NULL,
name VARCHAR(100),
occupation VARCHAR(100),
salary INT,
join_date DATE
}
Și acum să scriem codul care va adăuga un obiect din clasa noastră Employee la bază:
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;
}
Simplu și clar. Metoda va funcționa excelent.
Citirea unui obiect Java dintr-o bază de date
Am învățat cum să scriem un obiect în baza de date, acum să scriem codul pentru a citi obiectul din baza de date. Să începem cu codul care citește un obiect din baza de date după ID-ul său:
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;
}
Și dacă nu avem nevoie de un singur obiect, ci de mai multe? O astfel de cerere este, de asemenea, ușor de scris. Să luăm toți angajații companiei noastre:
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;
}
Apropo, dacă există multe astfel de metode, atunci în fiecare dintre ele va trebui să scrieți același cod pentru a converti șirul ResultSet într-un obiectangajat. Deci, acest cod poate fi mutat într-o metodă separată.
Acest lucru poate fi util mai ales dacă clasa Employee conține câmpuri complexe precum Enum, InputStream sau referințe la alte obiecte pe care dorim să le stocăm și în baza de date.
GO TO FULL VERSION