Commit f72a71a6 by Patryk Czarnik

Pierwsze przykłady JDBC

parent 01de5718
...@@ -14,4 +14,14 @@ ...@@ -14,4 +14,14 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> </properties>
<dependencies>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.7.4</version>
<scope>runtime</scope>
</dependency>
</dependencies>
</project> </project>
\ No newline at end of file
package p21_jdbc.bazowe;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class A_Polaczenie {
public static void main(String[] args) {
String url = "jdbc:postgresql://vps-2bc225bd.vps.ovh.net/hr";
try {
// W starszych wersjach Javy trzeba było wymusić załadowanie klasy sterownika do JVM
// Od ~ Java 7 już tego robić nie trzeba
// Class.forName("org.postgresql.Driver");
Connection c = DriverManager.getConnection(url, "alx", "abc123vps");
System.out.println("Nawiązano połączenie: " + c);
c.close();
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
package p21_jdbc.bazowe;
import java.sql.*;
public class B_PierwszySelect {
public static void main(String[] args) {
String url = "jdbc:postgresql://vps-2bc225bd.vps.ovh.net/hr";
try(Connection c = DriverManager.getConnection(url, "alx", "abc123vps")) {
System.out.println("Połączenie: " + c);
try(PreparedStatement stmt = c.prepareStatement("SELECT * FROM employees")) {
try(ResultSet rs = stmt.executeQuery()) {
System.out.println("ResultSet: " + rs);
while(rs.next()) {
System.out.printf("Pracownik nr %d: %s %s (%s) zarabia %s%n",
rs.getInt(1), // albo rs.getInt("employee_id")
rs.getString("first_name"),
rs.getString("last_name"),
rs.getString("job_id"),
rs.getBigDecimal("salary")
);
}
}
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment