Welcome to Halil Demirezen's Tips and Tutorials Page
Personal
Home
Contact
Biography
Research

Projects
Tutorials
Celsus Library (TR)

Categories

LinuxNetworkComputer VisionDatabasesProgramming
vmware


Postgresql Java SQL example from command line 2021-06-01 23:31:09


import java.util.*;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;

public class Conn {

public static void main(String[] args){
String url = "jdbc:postgresql://1.1.1.1/database ";
Statement stmt = null;
ResultSet rs = null;
Properties props = new Properties();
props.setProperty("user","username");
props.setProperty("password","password");
props.setProperty("ssl","false");
try {

// String sql = "INSERT INTO test(id) VALUES(11) RETURNING id";
String sql = "select * from test";
Connection conn = DriverManager.getConnection(url, props);
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);

/* below is example of select query
comment-out if you need insert only */
if(rs != null){
while(rs.next()){
int id = rs.getInt("id");
System.out.println(id);
}
}
/* end */
conn.close();
} catch (Exception e){
System.out.println(e.toString());
}
}
}


- Download Postgresql-42.2.20.jar (Not that the version number may change)

- Change SQL query in Conn.java for pupose

- Compile with
javac Conn.java


- Run with

java -cp postgresql-42.2.20.jar:. Conn