postgresql-demos/java/PostgresqlDemo.java
2018-12-21 16:03:06 -03:00

54 lines
1.7 KiB
Java

import java.sql.*;
import java.util.Properties;
import static java.lang.System.exit;
public class PostgresqlDemo {
private Connection conn;
private PostgresqlDemo() {
String url = "jdbc:postgresql://localhost/databasename";
Properties props = new Properties();
props.setProperty("user", "bdd");
props.setProperty("password", "bdd");
try {
conn = DriverManager.getConnection(url, props);
}
catch (SQLException e) {
e.printStackTrace();
exit(1);
}
try {
Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM turista");
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
System.out.printf("%-20s", resultSetMetaData.getColumnName(i));
}
System.out.print("\n\n");
while (resultSet.next()) {
for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
Object object = resultSet.getObject(i);
System.out.printf("%-20s", object == null ? "NULL" : object.toString());
}
System.out.print("\n");
}
resultSet.close();
statement.close();
}
catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new PostgresqlDemo();
}
}