Skip to content

Instantly share code, notes, and snippets.

@rhossi
Created November 20, 2016 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rhossi/b10c0cd20ac0284d758da405886a0320 to your computer and use it in GitHub Desktop.
Save rhossi/b10c0cd20ac0284d758da405886a0320 to your computer and use it in GitHub Desktop.
import java.sql.*;
import java.util.*;
public class JDBCExample {
public static void main(String[] argv) {
Connection connection = null;
Statement dropCreate = null;
Statement insert = null;
Statement select = null;
ResultSet results = null;
try {
// connection = DriverManager.getConnection(
// "jdbc:postgresql://ec2-xx-xxx-xxx-xx.compute-1.amazonaws.com:5432/dev", "user",
// "password");
connection = DriverManager.getConnection(
"jdbc:redshift://ec2-xx-xxx-xxx-xx.compute-1.amazonaws.com:5432/dev", "user",
"password");
connection.setAutoCommit(true);
dropCreate = connection.createStatement();
dropCreate.executeUpdate("drop table if exists testtable; create table testtable (testcol int);");
insert = connection.createStatement();
insert.executeUpdate("insert into testtable(testcol) values(1)");
select = connection.createStatement();
results = select.executeQuery("SELECT * FROM testtable;");
int testCol;
while(results.next()){
testCol = results.getInt("testcol");
String output = String.format("testcol = %s", testCol);
System.out.println(output);
}
if (results != null) { results.close(); }
if (dropCreate != null) { dropCreate.close(); }
if (insert != null) { insert.close(); }
if (select != null) { select.close(); }
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment