Last active
November 21, 2016 20:56
-
-
Save 4e1e0603/a379b0e03f3e92c2c2646de5b80f8aa2 to your computer and use it in GitHub Desktop.
Simple JDBC Java examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
This example shows how to connect to PostgreSQL database server using the `DriverManager` class. | |
It is recommended to use `DataSource` class instead because of connection pooling. | |
compile: javac DatabaseConnectionDemo.java | |
execute: java -cp .;lib\postgresql-X.X.XXXX.jar DatabaseConnectionDemo | |
*/ | |
//package io.uetoyo.gists; | |
import java.sql.Connection; | |
import java.sql.SQLException; | |
import java.sql.DriverManager; | |
class DatabaseConnectionDemo { | |
public static void main(String[] args) { | |
Connection connection = null; | |
String url = "jdbc:postgresql://SERVER_NAME/DATABASE_NAME"; | |
try { | |
connection = DriverManager.getConnection(url, "USER", "PASSWORD"); | |
System.out.println("Success"); | |
} catch (SQLException ex) { | |
System.out.println("Error"); | |
} finally { | |
if (connection != null) { | |
try { | |
connection.close(); | |
} catch (SQLException ex) { | |
// Handle or ignore the exception. | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment