Commit 47f4457c by Patryk Czarnik

Pierwsze połączenie Java - PostgreSQL

parent 5ea4b15a
......@@ -9,5 +9,13 @@
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
\ No newline at end of file
<dependencies>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.5.0</version>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>
package hello;
public class Hello {
public static void main(String[] args) {
}
}
package zajecia.postgresql;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Odczyt1 {
public static void main(String[] args) {
String url = "jdbc:postgresql://localhost:5432/hr";
try {
Connection c = DriverManager.getConnection(url, "kurs", "abc123");
System.out.println("Udało się połączyć, c = " + c);
PreparedStatement stmt = c.prepareStatement("SELECT * FROM employees");
ResultSet rs = stmt.executeQuery();
System.out.println("Mam wyniki: " + rs);
System.out.println();
// rs.next() próbuje przejść do nast. wiersza i zwraca true, jeśli się udało, a false, jeśli nie ma już nast. wiersza
while(rs.next()) {
// będąc w jakimś wierszu z rs można odczytywać wartości poszczególnych pól podając
// numer kolumny od 1
int id = rs.getInt(1);
String firstName = rs.getString(2);
String lastName = rs.getString(3);
// lub nazwę kolumny
String job = rs.getString("job_id");
BigDecimal salary = rs.getBigDecimal("salary");
System.out.printf("Pracownik nr %d: %s %s (%s), zarabia %s\n",
id, firstName, lastName, job, salary);
}
rs.close();
stmt.close();
c.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
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