Skip to content

Instantly share code, notes, and snippets.

@telmotrooper
Last active February 7, 2017 01:59
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 telmotrooper/00bfa957b3270980c5c9d1c0b3919a00 to your computer and use it in GitHub Desktop.
Save telmotrooper/00bfa957b3270980c5c9d1c0b3919a00 to your computer and use it in GitHub Desktop.
Basic PostgreSQL/Java example
import java.sql.*;
public class DBGuy {
private Connection c = null;
public DBGuy() {
try {
Class.forName("org.postgresql.Driver");
c = DriverManager
.getConnection("jdbc:postgresql://localhost:5432/testdb",
"user", "pass");
} catch(Exception e) {
e.printStackTrace();
System.exit(0);
}
System.out.println("Opened database sucessfully.");
}
public void createCompanyTable() {
Statement s = null;
try {
s = c.createStatement();
String sql = "CREATE TABLE COMPANY (" +
"ID INT PRIMARY KEY NOT NULL," +
"NAME TEXT NOT NULL," +
"AGE INT NOT NULL," +
"ADDRESS CHAR(50)," +
"SALARY REAL)";
s.executeUpdate(sql);
s.close();
} catch(Exception e) {
e.printStackTrace();
System.exit(0);
}
System.out.println("Company table created successfully.");
}
public void deleteCompanyTable() {
Statement s = null;
try {
s = c.createStatement();
String sql = "DROP TABLE IF EXISTS COMPANY";
s.execute(sql);
} catch(Exception e) {
e.printStackTrace();
System.exit(0);
}
}
public void closeConnection() {
try {
c.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
System.out.println("Connection closed.");
}
}
/*
https://www.tutorialspoint.com/postgresql/postgresql_java.htm
http://www.cheat-sheets.org/sites/sql.su/
PRIMARY KEY
The primary key consists of one or more columns
whose data contained within is used to uniquely
identify each row in the table. You can think of
the primary key as an address. If the rows in a
table were mailboxes, then the primary key would
be the listing of street addresses.
FOREIGN KEY
A foreign key is a set of one or more columns in
a table that refers to the primary key in another
table.
SQL EXAMPLE
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
)
*/
public class HelloWorld {
public static void main(String[] args) {
DBGuy dbg = new DBGuy();
dbg.deleteCompanyTable();
dbg.createCompanyTable();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment