Vollständige Liste der JDBC-Datentypen
Zusätzlich zu den Ihnen bekannten Datentypen ermöglicht Ihnen JDBC die Arbeit mit vielen nativen Datentypen für das DBMS. Im Folgenden werde ich die Typen und die Funktionen auflisten, um sie zu erhalten:
Typ | Methode |
---|---|
Array | getArray() |
AsciiStream | getAsciiStream() |
BigDecimal | getBigDecimal() |
BinaryStream | getBinaryStream() |
Klecks | getBlob() |
Boolescher Wert | getBoolean() |
Klecks | getBlob() |
Boolescher Wert | getBoolean() |
Bytes | getByte() |
Bytes | getBytes() |
CharacterStream | getCharacterStream() |
Klopf | getClob() |
Datum | Verabredung bekommen() |
Doppelt | getDouble() |
schweben | getFloat() |
int | getInt() |
Lang | getLong() |
NCharacterStream | getNCharacterStream() |
Objekt | getObject() |
Ref | getRef() |
RowId | getRowId() |
kurz | getShort() |
SQLXML | getSQLXML() |
Zeichenfolge | getString() |
Zeit | Zeit bekommen() |
Zeitstempel | getTimestamp() |
UnicodeStream | getUnicodeStream() |
URL | getURL() |
Wir haben bereits primitive Typen betrachtet. Versuchen wir nun, mit Objekten zu arbeiten.
BLOB-Datentyp
Wenn Sie ein Objekt in der Datenbank speichern möchten, ist die Verwendung des SQL-BLOB-Typs der einfachste Weg, dies zu tun. JDBC hat sein Gegenstück namens Blob.
BLOB steht für Binary Large Object . _ Es wird zum Speichern eines Arrays von Bytes verwendet. Der Blob-Typ in JDBC ist eine Schnittstelle und Sie können Daten auf zwei Arten darin ablegen (und empfangen):
- Verwenden von InputStream
- Verwendung eines Arrays von Bytes
Beispiel: Spalte Nummer 3 enthält den BLOB-Typ:
Statement statement = connection.createStatement();
ResultSet results = statement.executeQuery("SELECT * FROM user");
results.first();
Blob blob = results.getBlob(3);
InputStream is = blob.getBinaryStream();
Um Ihr eigenes Blob-Objekt zu erstellen, müssen Sie die Funktion createBlob() verwenden . Beispiel:
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();
Es gibt zwei Möglichkeiten, einen Blob mit Daten zu füllen. Der erste geht über OutputSteam :
Path avatar = Paths.get("E:\\images\\cat.jpg");
OutputStream os = blob.setBinaryStream(1);
Files.copy(avatar, os);
Und das zweite - durch Füllen mit Bytes:
Path avatar = Paths.get("E:\\images\\cat.jpg");
byte[] content = Files.readAllBytes(avatar);
blob.setBytes(1, content);
Speichern eines Java-Objekts in einer Datenbank
Wir haben gelernt, wie man binäre Objekte in der Datenbank speichert: Byte-Arrays, Byte-Streams und so weiter. Was ist mit Java-Objekten? Wie speichern wir ein Java-Objekt in einer Datenbank?
Nehmen wir an, wir haben eine Employee- Java-Klasse , die einen Mitarbeiter eines Unternehmens beschreibt:
public class Employee {
public Integer id;
public String name;
public String occupation;
public Integer salary;
public Date joinDate;
}
Wie können wir ein Objekt dieser Klasse mit JDBC in der Datenbank speichern?
Tatsächlich wissen Sie bereits alles, was Sie wissen müssen. Zuerst müssen Sie in der Datenbank eine Tabelle erstellen, die dieser Klasse entspricht. Zum Beispiel dieses hier:
CREATE TABLE employee {
id INT PRIMARY KEY NOT NULL,
name VARCHAR(100),
occupation VARCHAR(100),
salary INT,
join_date DATE
}
Und jetzt schreiben wir den Code, der der Basis ein Objekt unserer Employee- Klasse hinzufügt :
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;
}
Einfach und klar. Die Methode wird großartig funktionieren.
Lesen eines Java-Objekts aus einer Datenbank
Wir haben gelernt, wie man ein Objekt in die Datenbank schreibt. Jetzt schreiben wir den Code, um das Objekt aus der Datenbank zu lesen. Beginnen wir mit dem Code, der ein Objekt anhand seiner ID aus der Datenbank liest:
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;
}
Und wenn wir nicht ein Objekt brauchen, sondern mehrere? Eine solche Anfrage ist auch einfach zu schreiben. Holen wir uns alle Mitarbeiter unseres Unternehmens:
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;
}
Wenn es viele solcher Methoden gibt, müssen Sie übrigens in jeder von ihnen den gleichen Code schreiben, um die ResultSet- Zeichenfolge in ein Objekt umzuwandelnMitarbeiter. Daher kann dieser Code in eine separate Methode verschoben werden.
Dies kann besonders nützlich sein, wenn die Employee- Klasse komplexe Felder wie Enum, InputStream oder Verweise auf andere Objekte enthält, die wir ebenfalls in der Datenbank speichern möchten.
GO TO FULL VERSION